1.單下划線
在python中單下划線代表私有,但也僅僅是名義上的私有,只是一種規范,告訴人們不要在外部使用它。但實際上python沒有真正意義上的私有,我們一樣可以在外部去調用私有方法或屬性。
class BaseForm(StrAndUnicode): def _get_errors(self): ''' Returns an ErrorDict for the data provided for the form :return: ''' if self._errors is None: self.full_clean() return self._errors errors = property(_get_errors)
該代碼片段來自Django源碼(django/forms/forms.py)。這段代碼的設計就是errors屬性是對外API的一部分,如果你想獲取錯誤詳情,應該訪問errors屬性,而不是(也不應該)訪問_get_errors方法。實際上我們仍然可以使用對象在外部調用它。
baseform = BaseForm()
baseform._get_errors()
2.雙下划線
雙下划線使用來避免父類方法被子類方法覆蓋的。雙下划線方法的本質是在方法前加了_類名,我們可以使用對象._類名__方法名(),來在外部調用它。
class A(object): def __method(self): print("I'm a method in class A") def method_x(self): print("I'm another method in class A\n") def method(self): self.__method() self.method_x() class B(A): def __method(self): print("I'm a method in class B") def method_x(self): print("I'm another method in class B\n") if __name__ == '__main__': print("situation 1:") a = A() a.method() b = B() b.method() print("situation 2:") #b.__method() 報錯 'B' object has no attribute '__method' a._A__method()
上面程序的執行結果為:
situation 1: I'm a method in class A I'm another method in class A I'm a method in class A I'm another method in class B situation 2: I'm a method in class A
3.前后雙下划線
前后雙下滑線方法是python自己定義出來,供自己調用的。這些方法會在特定的條件下被觸發執行。下面是常用的一些前后雙下划線方法。
__str__ 當將對象轉換成字符串時會執行 __init__ 初始化方法,為對象變量賦值 __new__ 構造方法,創建一個對象 __call__ 在對象后面加括號會執行該方法 __getattr__ 當使用對象.屬性時,若屬性不存在會調用該方法 __setattr__ 當使用對象.屬性 = 值,會調用該方法 __iter__ 類內部定義了該方法,對象就變成了可迭代對象 __add__ 當兩個對象使用+號會調用該方法 __enter__和__exit__ 上下文管理 class Foo(object): def __enter__(self): print('開始') return Foo() def __exit__(self, exc_type, exc_val, exc_tb): print('結束') with Foo() as obj: #with后面的Foo()會執行__enter__()方法,並將返回值賦給obj print(123) #縮進代碼執行完成后會執行__exit__()方法 #開始 #123 #結束
我們可以在自己的類中重寫者些方法,以便實現特定的功能。
以上大部分內容參考自https://www.jb51.net/article/129534.htm