class A(object):
def __init__(self):
self._protected = 10
self.__private = 50
def test(self):
print self.__private
a =A()
a.test()
print a._protected,a.__private
A._protected
50
10
Traceback (most recent call last):
File "E:\python\test2.py", line 17, in <module>
print a._protected,a.__private
AttributeError: 'A' object has no attribute '__private'
Traceback (most recent call last):
File "E:\python\test2.py", line 20, in <module>
print A._protected
AttributeError: type object 'A' has no attribute '_protected'
_var ;变量名前一个下划线来定义,此变量为保护成员protected,只有类及其子类可以访问。此变量不能通过from XXX import xxx 导入
__var;变量名前两个下划线来定义,此变量为私有private,只允许类本身访问,连子类都不可以访问。
网友评论