示例
>>>
class student(object):
__name = 0
_sex = 'male'
>>> student.__dict__
mappingproxy({'__module__': '__main__', '_student__name': 0, '_sex': 'male', '__dict__': <attribute '__dict__' of 'student' objects>, '__weakref__': <attribute '__weakref__' of 'student' objects>, '__doc__': None})
>>> student.__name
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <module>
student.__name
AttributeError: type object 'student' has no attribute '__name'
>>> student._student__name
>>> student._sex
'male'
认真看 ,细心地你会发现问题所在
总结:我们声明了一个学生类,分别用但下划线和双下划线定义了一个成员,然后我们试图访问成员,我们发现:双下划线的成员无法直接访问,通过__dict__我们看到,在类的内部,Python自动将__name 解释成 _student__name,于是我们用 _student__name访问,这次成功。然而,_name不受影响。所以:
两头下划线:Python类内置成员专用,区别用户自定义成员
单下划线:类的普通成员
爽下划线:解析器自动转换为:_类名__成员名,代替原有成员,访问需要在原有成员名字前加上_类名。