示例
>>>
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類內置成員專用,區別用戶自定義成員
單下劃線:類的普通成員
爽下劃線:解析器自動轉換爲:_類名__成員名,代替原有成員,訪問需要在原有成員名字前加上_類名。