_xx 單下划線開頭
Python中沒有真正的私有屬性或方法,可以在你想聲明為私有的方法和屬性前加上單下划線,以提示該屬性和方法不應在外部調用.如果真的調用了也不會出錯,但不符合規范.
Python中不存在真正的私有方法。為了實現類似於c++中私有方法,可以在類的方法或屬性前加一個“_”單下划線,意味着該方法或屬性不應該去調用,它並不屬於API。
在使用property時,經常出現這個問題:
class BaseForm(StrAndUnicode): ... def _get_errors(self): "Returns an ErrorDict for the data provided for the form" if self._errors is None: self.full_clean() return self._errors errors = property(_get_errors)
上面的代碼片段來自於django源碼(django/forms/forms.py)。這里的errors是一個屬性,屬於API的一部分,但是_get_errors是私有的,是不應該訪問的,但可以通過errors來訪問該錯誤結果。
"__"雙下划線
這個雙下划線更會造成更多混亂,但它並不是用來標識一個方法或屬性是私有的,真正作用是用來避免子類覆蓋其內容。
讓我們來看一個例子:
class A(object): def __method(self): print "I'm a method in A" def method(self): self.__method() a = A() a.method()
輸出是這樣的:
$ python example.py I'm a method in A
很好,出現了預計的結果。
我們給A添加一個子類,並重新實現一個__method:
class B(A): def __method(self): print "I'm a method in B" b = B() b.method()
現在,結果是這樣的:
$ python example.py I'm a method in A
就像我們看到的一樣,B.method()不能調用B.__method的方法。實際上,它是"__"兩個下划線的功能的正常顯示。
因此,在我們創建一個以"__"兩個下划線開始的方法時,這意味着這個方法不能被重寫,它只允許在該類的內部中使用。
在Python中如是做的?很簡單,它只是把方法重命名了,如下:
a = A() a._A__method() # never use this!! please!
$ python example.py I'm a method in A
如果你試圖調用a.__method,它還是無法運行的,就如上面所說,只可以在類的內部調用__method。
"__xx__"前后各雙下划線
當你看到"__this__"的時,就知道不要調用它。為什么?因為它的意思是它是用於Python調用的,如下:
>>> name = "igor" >>> name.__len__() 4 >>> len(name) 4 >>> number = 10 >>> number.__add__(20) 30 >>> number + 20 30
“__xx__”經常是操作符或本地函數調用的magic methods。在上面的例子中,提供了一種重寫類的操作符的功能。
在特殊的情況下,它只是python調用的hook。例如,__init__()函數是當對象被創建初始化時調用的;__new__()是用來創建實例。
class CrazyNumber(object): def __init__(self, n): self.n = n def __add__(self, other): return self.n - other def __sub__(self, other): return self.n + other def __str__(self): return str(self.n) num = CrazyNumber(10) print num # 10 print num + 5 # 5 print num - 20 # 30
另一個例子
class Room(object): def __init__(self): self.people = [] def add(self, person): self.people.append(person) def __len__(self): return len(self.people) room = Room() room.add("Igor") print len(room) # 1
結論
- 使用_one_underline來表示該方法或屬性是私有的,不屬於API;
- 當創建一個用於python調用或一些特殊情況時,使用__two_underline__;
- 使用__just_to_underlines,來避免子類的重寫!