python單/雙底線使用

來源:互聯網
上載者:User

標籤:ror   機制   name   sys   ble   erro   python編程   c++   odi   

在Python編程中經常會遇到函數(function),方法(method)及屬性(attribute)以底線‘_‘作為首碼,這裡做個總結。

主要存在四種情形:
1 1. object # public2 2. __object__ # special, python system use, user should not define like it3 3. __object # private (name mangling during runtime)4 4. _object # obey python coding convention, consider it as private
1和2兩種情形比較容易理解,不多做解釋,最迷惑人的就是3和4情形。在解釋3和4情形前,首先瞭解下python有關private的描述,python中不存在protected的概念,要麼是public要麼就是private,但是python中的private不像C++, Java那樣,它並不是真正意義上的private,通過name mangling(名稱改編,下面例子說明)機制就可以訪問private了。
 1 class Foo(): 2     def __init__(): 3         ...  4     def public_method(): 5         print ‘This is public method‘ 6     def __fullprivate_method(): 7         print ‘This is double underscore leading method‘ 8     def _halfprivate_method(): 9         print ‘This is one underscore leading method‘10 11 f = Foo()12 f.public_method() # OK13 f.__fullprivate_method() # Error occur14 f._halfprivate_method() # OK

上文已經說明了,python中並沒有真正意義的private,見以下方法便能夠訪問__fullprivate_method()

  

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.