標籤: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單/雙底線使用