轻松理解python中的_和__区别和含义
Python中 _ 和 __ 的含義
_ 的含義
在python的類中,沒有真正的私有化,不管是方法還是屬性,為了編程的需要,約定加了下劃線 _ 的屬性和方法不屬于API,不應該在類的外面訪問,也不會被from M import * 導入。下面的代碼演示加了_ 的方法,以及在類外面對其的可訪問性。
class A:def _method(self):print('約定為不在類的外面直接調用這個方法,但是也可以調用')def method(self):return self._method() a = A()在類A中定義了一個_method方法,按照約定是不能在類外面直接調用它的,為了可以在外面使用_method方法,又定義了method方法,method方法調用_method方法。請看代碼演示:
In [24]: a.method() 不建議在類的外面直接調用這個方法,但是也可以調用但是我們應該記住的是加了_的方法也可以在類外面調用:
In [25]: a._method() 不建議在類的外面直接調用這個方法,但是也可以調用__ 的含義
python中的__和一項稱為name mangling的技術有關,name mangling (又叫name decoration命名修飾).在很多現代編程語言中,這一技術用來解決需要唯一名稱而引起的問題,比如命名沖突/重載等. [ 維基百科 ]
代碼演示如下:
------------------------------------------------------------------ [ --注:我這有個學習基地,里面有很多學習資料,感興趣的+Q群:895817687] ------------------------------------------------------------------ class A:def __method(self):print('This is a method from class A')def method(self):return self.__method()class B(A):def __method(self):print('This is a method from calss B')在類A中,__method方法其實由于name mangling技術的原因,變成了_A__method,所以在A中method方法返回的是_A__method,B作為A的子類,只重寫了__method方法,并沒有重寫method方法,所以調用B中的method方法時,調用的還是_A__method方法:
In [27]: a = A()In [28]: b = B()In [29]: a.method() This is a method from class AIn [30]: b.method() This is a method from class A在A中沒有__method方法,有的只是_A__method方法,也可以在外面直接調用,所以python中沒有真正的私有化:
-------------------------------------------------------------------- [ --注:我這有個學習基地,里面有很多學習資料,感興趣的+Q群:895817687] --------------------------------------------------------------------In [35]: a.__method()AttributeError Traceback (most recent call last) <ipython-input-35-b8e0b1bf4d09> in <module>() ----> 1 a.__method()AttributeError: 'A' object has no attribute '__method'In [36]: a._A__method() This is a method from class A在B中重寫method方法:
class B(A):def __method(self):print('This is a method from calss B')def method(self):return self.__method()現在B中的method方法會調用_B__method方法:
In [32]: b = B()In [33]: b.method() This is a method from calss B總結
python中沒有真正的私有化,但是有一些和命名有關的約定,來讓編程人員處理一些需要私有化的情況。
總結
以上是生活随笔為你收集整理的轻松理解python中的_和__区别和含义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在面试中介绍自己的项目经验,90%的
- 下一篇: Python 骚操作,微信远程控制电脑