Python中單底線,雙底線,倆頭底線的區別。__Python

來源:互聯網
上載者:User

樣本

>>>     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.__nameTraceback (most recent call last):  File "<pyshell#58>", line 1, in <module>    student.__nameAttributeError: type object 'student' has no attribute '__name'>>> student._student__name>>> student._sex'male'

認真看 ,細心地你會發現問題所在

    總結:我們聲明了一個學生類,分別用但底線和雙底線定義了一個成員,然後我們試圖訪問成員,我們發現:雙底線的成員無法直接存取,通過__dict__我們看到,在類的內部,Python自動將__name 解釋成 _student__name,於是我們用 _student__name訪問,這次成功。然而,_name不受影響。所以:兩頭底線:Python類內建成員專用,區別使用者自訂成員單底線:類的普通成員爽底線:解析器自動轉換為:_類名__成員名,代替原有成員,訪問需要在原有成員名字前加上_類名。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.