Python 中的靜態類變數
 
Python 中的靜態變數是在定義的類中宣告但不在方法中宣告的變數。該變數可以通過定義它的類呼叫,但不能直接呼叫。靜態變數也稱為類變數。這些變數僅限於類,因此它們不能更改物件的狀態。
本教程將演示在 Python 中定義靜態變數的不同方法。
在 Python 中使用 staticmethod() 定義靜態變數
Python 中的 staticmethod() 是一個內建函式,用於返回給定函式的靜態變數。
這種方法現在被認為是在 Python 中定義靜態變數的舊方法。
例子:
class StaticVar:
    def random(text):
        print(text)
        print("This class will print random text.")
StaticVar.random = staticmethod(StaticVar.random)
StaticVar.random("This is a random class.")
輸出:
This is a random class.
This class will print random text.
在這裡,首先,我們建立一個名為 StaticVar 的類。在程式中,我們使用 staticmethod() 函式在類外宣告一個名為 random 的變數作為靜態變數。通過這個,我們可以直接使用 StaticVar 類呼叫 random()。
在 Python 中使用 @staticmethod 定義靜態變數
@staticmethod 是一種現代且最常用的定義靜態變數的方法。@staticmethod 是 Python 中的內建裝飾器。裝飾器是 Python 中的一種設計模式,用於在不改變其初始結構的情況下為已經存在的物件新增新功能。因此,@staticmethod 裝飾器用於在 Python 的類中定義靜態變數。
例子:
class StaticVar:
    @staticmethod
    def random(text):
        # show custom message
        print(text)
        print("This class will print random text.")
StaticVar.random("This is a random class.")
輸出:
This is a random class.
This class will print random text.
請注意,@staticmethod 裝飾器是在定義靜態變數 random 之前定義的。因此,我們可以輕鬆地通過 StaticVar 類在末尾呼叫 random 變數。
另外,請注意,在這兩種方法中,我們都沒有使用 self 引數,該引數用於在定義 random 變數時訪問函式屬性和方法。這是因為靜態變數永遠不會通過物件進行操作。
Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.
LinkedIn