私有成员和公有成员
属性名以两个画线“_ _”开头则表示是私有成员
class Person:
num = 0
def __init__(self,str,n,w):
self.name = str
self.age = n
self.__weight = w
Person.num +=1
P1 = Person("夏敏捷",20,120)
P2 = Person("张海",39,130)
print(P1.name)
print(P1._Person__weight)
print(P1.__weight)
输出结果
夏敏捷
120
AttributeError: ‘Person’ object has no attribute ‘__weight’
最后一句由于不能直接访问私有成员所以出现AttributeError: ‘Person’ object has no attribute ‘__weight’
- _xxx: 这样的对象叫作保护成员
- _ _xxx _ _:系统定义的特列成员
- __xxx:类中的私有成员,只有类自己内部成员方法函数能访问