Python class instance attributes and attribute

Class has attributes for all instances, a single instance of the instance attribute have

class CLS(object):
    count = 0
    _count = 0
    def __init__(self):
        CLS.count = CLS.count + 1
        self._count = self._count + 1
        
p=CLS() 
print('类属性:%d'%p.count)
print('实例属性:%d'%p._count)

p=CLS() 
print('类属性:%d'%p.count)
print('实例属性:%d'%p._count)

p=CLS()
print('类属性:%d'%p.count)
print('实例属性:%d'%p._count)
类属性:1
实例属性:1
类属性:2
实例属性:1
类属性:3
实例属性:1

When an instance of the same name attributes and class attributes, examples of high-priority attribute

class CLS(object):
    count = 0
    def __init__(self):
        self.count = self.count + 1
        CLS.count = CLS.count + 1
        
p=CLS() 
print('类属性:%d'%p.count)
print('实例属性:%d'%p.count)

p=CLS() 
print('类属性:%d'%p.count)
print('实例属性:%d'%p.count)

p=CLS()
print('类属性:%d'%p.count)
print('实例属性:%d'%p.count)
Published 239 original articles · won praise 68 · views 180 000 +

Guess you like

Origin blog.csdn.net/weixin_42078760/article/details/104114663