新聞中心
在看一些Python開源代碼時(shí),經(jīng)常會(huì)看到以下劃線或者雙下劃線開頭的方法或者屬性,到底它們有什么作用,又有什么樣的區(qū)別呢?今天我們來總結(jié)一下(注:下文中的代碼在Python3下測(cè)試通過)

我們提供的服務(wù)有:成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、微信公眾號(hào)開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、良慶ssl等。為近千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的良慶網(wǎng)站制作公司
_ 的含義
在python的類中沒有真正的私有屬性或方法,沒有真正的私有化。
但為了編程的需要,我們常常需要區(qū)分私有方法和共有方法以方便管理和調(diào)用。那么在Python中如何做呢?
一般Python約定加了下劃線 _ 的屬性和方法為私有方法或?qū)傩?,以提示該屬性和方法不?yīng)在外部調(diào)用,也不會(huì)被from ModuleA import * 導(dǎo)入。如果真的調(diào)用了也不會(huì)出錯(cuò),但不符合規(guī)范。
下面的代碼演示加了_ 的方法,以及在類外面對(duì)其的可訪問性。
class TestA:
def _method(self):
print('I am a private function.')
def method(self):
return self._method()
ca = TestA()
ca.method()
輸出
I am a private function.
__ 的含義
Python中的__和一項(xiàng)稱為name mangling的技術(shù)有關(guān),name mangling (又叫name decoration命名修飾).在很多現(xiàn)代編程語言中,這一技術(shù)用來解決需要唯一名稱而引起的問題,比如命名沖突/重載等.
Python中雙下劃線開頭,是為了不讓子類重寫該屬性方法.通過類的實(shí)例化時(shí)自動(dòng)轉(zhuǎn)換,在類中的雙下劃線開頭的屬性方法前加上”_類名”實(shí)現(xiàn).
class TestA:
def __method(self):
print('This is a method from class TestA')
def method(self):
return self.__method()
class TestB(TestA):
def __method(self):
print('This is a method from calss TestB')
ca = TestA()
cb = TestB()
ca.method()
cb.method()
輸出結(jié)果
This is a method from class TestA This is a method from class TestB
在類TestA中,__method方法其實(shí)由于name mangling技術(shù)的原因,自動(dòng)轉(zhuǎn)換成了_TestA__method,所以在A中method方法返回的是_TestA__method,TestB作為TestA的子類,只重寫了__method方法,并沒有重寫method方法,所以調(diào)用B中的method方法時(shí),調(diào)用的還是_TestA__method方法。
注意:在A中沒有__method方法,有的只是_A__method方法,也可以在外面直接調(diào)用,所以python中沒有真正的私有化
不能直接調(diào)用__method()方法, 需要調(diào)用轉(zhuǎn)換之后的方法
ca.__method()
輸出
Traceback (most recent call last): File "", line 1, in AttributeError: 'TestA' object has no attribute '__method'
轉(zhuǎn)換后的方法名為:_TestA__method
ca._TestA__method()
輸出
This is a method from class TestA
在TestB中重寫method方法:
class TestB(TestA):
def __method(self):
print('This is a method from calss TestB')
def method(self):
return self.__method()
cb = B()
cb.method()
輸出
This is a method from calss TestB
現(xiàn)在TestB中的method方法會(huì)調(diào)用_TestB__method方法。
總結(jié)
python中沒有真正的私有化,但是有一些和命名有關(guān)的約定,來讓編程人員處理一些需要私有化的情況。
文章名稱:創(chuàng)新互聯(lián)Python教程:Python3中_和__的用途和區(qū)別
文章起源:http://fisionsoft.com.cn/article/cdicsgo.html


咨詢
建站咨詢
