Python程式中的私有變數
在本教程中,我們將學習Python **類**中的**私有變數**。
Python沒有所謂的**私有變數**的概念。但是,大多數Python開發人員遵循一種命名約定來表明變數不是公共的,而是私有的。
我們必須以**雙下劃線**開頭變數名來將其表示為私有變數(實際上並非如此)。例如:**one、two等等**。
正如我們已經說過的,名稱以雙下劃線開頭的變數並非私有。我們仍然可以訪問它們。讓我們看看如何建立私有型別的變數,然後我們將看到如何訪問它們。
# creating a class
class Sample:
def __init__(self, nv, pv):
# normal variable
self.nv = nv
# private variable(not really)
self.__pv = pv
# creating an instance of the class Sample
sample = Sample('Normal variable', 'Private variable')我們建立了一個類及其例項。我們在`__init__`方法中定義了兩個變數,一個是普通的,另一個是私有的。現在,嘗試訪問這些變數,看看會發生什麼。
示例
# creating a class
class Sample:
def __init__(self, nv, pv):
# normal variable
self.nv = nv
# private variable(not really)
self.__pv = pv
# creating an instance of the class Sample
sample = Sample('Normal variable', 'Private variable')
# accessing *nv*
print(sample.nv)
# accessing *__pv**
print(sample.__pv)輸出
如果執行以上程式碼,則會得到以下輸出。
Normal variable --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-bc324b2d20ef> in <module> 14 15 # accessing *__pv** ---> 16 print(sample.__pv) AttributeError: 'Sample' object has no attribute '__pv'
程式顯示了nv變數,沒有任何錯誤。但是當我們嘗試訪問`__pv`變數時,我們得到了**AttributeError**。
為什麼會出現此錯誤?因為沒有名為`__pv`的屬性。那麼`__init__`方法中的`self.__pv = pv`語句呢?我們稍後會討論這個問題。首先,讓我們看看如何訪問`__pv`變數。
我們可以訪問任何名稱以**雙下劃線**開頭的類變數,方法是使用`_className__variableName_`。因此,在我們的示例中,它是`_Sample__pv_`。現在,使用`_Sample__pv_`名稱訪問它。
示例
# creating a class
class Sample:
def __init__(self, nv, pv):
# normal variable
self.nv = nv
# private variable(not really)
self.__pv = pv
# creating an instance of the class Sample
sample = Sample('Normal variable', 'Private variable')
# accessing *nv*
print(sample.nv)
# accessing *__pv** using _Sample__pv name
print(sample._Sample__pv)輸出
如果執行以上程式碼,則會得到以下結果。
Normal variable Private variable
為什麼變數`__pv`的名稱發生了變化?
在Python中,有一個名為名稱改編(name mangling)的概念。Python會更改以**雙下劃線**開頭的變數的名稱。因此,任何名稱以雙下劃線開頭的類變數都會更改為`_className__variableName_`的形式。
因此,此概念也適用於類的 方法。您可以使用以下程式碼檢視它。
示例
class Sample: def __init__(self, a): self.a = a # private method(not really) def __get_a(self): return self.a # creating an instance of the class Sample sample = Sample(5) # invoking the method with correct name print(sample._Sample__get_a()) # invoking the method with wrong name print(sample.__get_a())
輸出
如果執行以上程式碼,則會得到以下結果。
5 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-19-55650c4990c8> in <module> 14 15 # invoking the method with wrong name ---> 16 print(sample.__get_a()) AttributeError: 'Sample' object has no attribute '__get_a'
結論
使用**雙下劃線**的目的不是為了限制訪問變數或方法。它是為了表明該特定變數或方法僅旨在繫結在類內部。如果您對本教程有任何疑問,請在評論區提出。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP