请问一下哪里错了?

提示第九行错误,Person类里面没有__count

提示第九行错误,Person类里面没有__count
2018-06-24
Python对属性权限的控制是通过属性名来实现的,如果一个属性由双下划线开头(__),该属性就无法被外部访问。看例子:
class Person(object):
def __init__(self, name):
self.name = name
self._title = 'Mr'
self.__job = 'Student'
p = Person('Bob')
print p.name
# => Bob
print p._title
# => Mr
print p.__job
# => Error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute '__job'可见,只有以双下划线开头的"__job"不能直接被外部访问。
所以,你可以这样子定义一个类方法,就可以获取了~
class Person(object):
__count = 0
def __init__(self, name):
Person.__count = Person.__count + 1
self.name = name
print Person.__count
@classmethod#类方法
def get_count(self):
return Person.__count
p1 = Person('Bob')
p2 = Person('Alice')
print Person.get_count()
举报