类属性和实例属性

  • 不要在实例中尝试修改类属性,虽然实例可以访问类属性,这相当于给实例增加了重名的实例属性。
class Person(object):
    address = 'zhejiang'
    def __init__(self, name):
        self.name = name
 
p1 = Person('Bob')
p2 = Person('Alice')
 
print 'Person.address = ' + Person.address  # zhejiang
 
p1.address = 'shanxi'
print 'p1.address = ' + p1.address  # shanxi
 
print 'Person.address = ' + Person.address   # zhejiang
print 'p2.address = ' + p2.address  # zhejiang
  • 类属性的访问和控制
class Person(object):
    count = 0
    @classmethod
    def how_many(cls):
        return cls.count
    def __init__(self, name):
        self.name = name
        Person.count = Person.count + 1
 
print Person.how_many()
p1 = Person('Bob')
print Person.how_many()
@classmethod
    def how_many(cls):
        return cls.count
    def __init__(self, name):
        self.name = name
        Person.count = Person.count + 1

print Person.how_many()
p1 = Person('Bob')
print Person.how_many()

代码来自

你可能感兴趣的:(PYTHON3,类属性)