Python 中的私有變數

Aditya Raj 2023年1月30日
  1. 什麼是 Python 中的私有變數
  2. 在 Python 中如何實現私有變數
  3. 在 Python 中訪問私有變數
  4. Python 私有變數的結論
Python 中的私有變數

私有變數在程式中用於訪問控制。Java 和 C++ 等程式語言已指定關鍵字來定義私有變數。

在 Python 中,我們沒有定義私有變數的關鍵字。本文將討論如何實現私有變數並使用類名訪問它們。

什麼是 Python 中的私有變數

我們不能在 Python 中建立私有變數,但我們可以使用特殊的命名約定來模擬私有變數的實現。

我們可以使用語法 objectName.attributeName 訪問物件的任何屬性。看例子。

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.SSN = SSN


person1 = Person(name="Alex", age=15, SSN=1234567890)
print("Name of the person is:", person1.name)
print("Age of the person is:", person1.age)
print("SSN of the person is:", person1.SSN)

輸出:

Name of the person is: Alex
Age of the person is: 15
SSN of the person is: 1234567890

我們建立了一個類 Person,其屬性為 nameageSSN。在建立 Person 類的例項 person1 後,我們使用語法 person1.nameperson1.ageperson1 在類外部訪問屬性 nameageSSN .SSN`。

我們不希望在類定義之外訪問 SSN。我們沒有任何關鍵字可以在 Python 中建立私有變數。那麼我們應該如何模擬私有變數的實現呢?

在 Python 中如何實現私有變數

為了在 Python 中實現私有變數,我們將在變數名前使用雙下劃線 (__)。讓我們使用雙下劃線定義 Person 類的屬性 SSN

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.__SSN = SSN

如果我們建立 Person 類的例項 person1 並使用語法 person1.__SSN 訪問屬性 __SSN,程式會顯示錯誤並引發下面的 AttributeError 異常。

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.__SSN = SSN


person1 = Person(name="Alex", age=15, SSN=1234567890)
print("Name of the person is:", person1.name)
print("Age of the person is:", person1.age)
print("SSN of the person is:", person1.__SSN)

輸出:

Name of the person is: Alex
Age of the person is: 15
/usr/lib/Python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/PythonProject/string1.py", line 11, in <module>
    print("SSN of the person is:", person1.__SSN)
AttributeError: 'Person' object has no attribute '__SSN'

我們可以訪問除 __SSN 之外的所有其他屬性。該程式說沒有名為 __SSN 的屬性。那麼我們如何訪問屬性 __SSN 中的值呢?

在 Python 中訪問私有變數

我們不能在類定義之外訪問私有變數,但我們可以在內部訪問它。因此,我們可以在類內部建立一個方法來訪問私有變數值。

我們可以建立一個名為 getSSN() 的方法,它返回屬性 __SSN 的值,如下所示。

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.__SSN = SSN

    def getSSN(self):
        return self.__SSN


person1 = Person(name="Alex", age=15, SSN=1234567890)
print("Name of the person is:", person1.name)
print("Age of the person is:", person1.age)
print("SSN of the person is:", person1.getSSN())

輸出:

Name of the person is: Alex
Age of the person is: 15
SSN of the person is: 1234567890

我們可以直接訪問私有變數,而不是定義方法。讓我們看看私有變數是如何儲存在記憶體中的。當我們用雙下劃線 (__) 定義變數名時,Python 直譯器會說沒有這樣的屬性。

要了解變數的儲存方式,我們將檢查給定物件的所有屬性。我們將使用 dir() 函式,它接受一個物件或輸入引數並返回所有物件屬性的列表。讓我們使用 dir() 函式檢查 person1 物件的屬性。

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.__SSN = SSN

    def getSSN(self):
        return self.__SSN


person1 = Person(name="Alex", age=15, SSN=1234567890)
print("Attributes of the Person are:")
print(dir(person1))

輸出:

Attributes of the Person are:
['_Person__SSN', '__doc__', '__init__', '__module__', 'age', 'getSSN', 'name']

觀察 nameage 屬性是否存在,但沒有 __SSN 屬性。但是,有一個名為 _Person__SSN 的屬性。讓我們為物件 person1 列印此屬性的值。

class Person:
    def __init__(self, name, age, SSN):
        self.name = name
        self.age = age
        self.__SSN = SSN

    def getSSN(self):
        return self.__SSN


person1 = Person(name="Alex", age=15, SSN=1234567890)
print("Name of the person is:", person1.name)
print("Age of the person is:", person1.age)
print("SSN of the person is:", person1._Person__SSN)

輸出:

Name of the person is: Alex
Age of the person is: 15
SSN of the person is: 1234567890

注意屬性 _Person__SSN__SSN 具有相同的值。屬性 __SSN 在程式中儲存為 _Person__SSN。每當我們訪問屬性 __SSN 時,程式都會遇到 AttributeError 異常。

在 Python 中,當我們使用雙下劃線 (__) 定義屬性時,程式會在屬性名稱前新增 _className。這個過程稱為重整。

Python 認為使用雙下劃線命名的屬性是修改中的私有變數。然而,這不是真的,因為我們可以使用語法 _className__attributeName 訪問變數。

Python 私有變數的結論

在本文中,我們討論了 Python 中的私有變數。我們已經看到,與其他程式語言不同,我們沒有任何特定的關鍵字來在 Python 中宣告私有變數。但是,我們可以通過使用雙下劃線字元命名變數來模擬私有變數的實現。

我們還討論了在 Python 中訪問私有變數的兩種方法。我們建議使用方法來訪問私有變數。使用帶有類名的方法將破壞實現私有變數的本質,因為我們將直接訪問該變數。該程式會警告你在屬性名稱之前使用 _className 訪問私有變數。

作者: Aditya Raj
Aditya Raj avatar Aditya Raj avatar

Aditya Raj is a highly skilled technical professional with a background in IT and business, holding an Integrated B.Tech (IT) and MBA (IT) from the Indian Institute of Information Technology Allahabad. With a solid foundation in data analytics, programming languages (C, Java, Python), and software environments, Aditya has excelled in various roles. He has significant experience as a Technical Content Writer for Python on multiple platforms and has interned in data analytics at Apollo Clinics. His projects demonstrate a keen interest in cutting-edge technology and problem-solving, showcasing his proficiency in areas like data mining and software development. Aditya's achievements include securing a top position in a project demonstration competition and gaining certifications in Python, SQL, and digital marketing fundamentals.

GitHub

相關文章 - Python Variable