06.11 Python 靜態方法 staticmethod 和 類方法 classmethod

Python 靜態方法 staticmethod 和 類方法 classmethod

這篇文章說一下 Python 類的靜態方法 staticmethod 和類方法 classmethod,以及他們有什麼不同。

他們都是作為方法的裝飾器使用。

實例方法 Instance Methods


通常一個類的方法是實例方法,方法的第一個參數是引用對象本身。例如:

Python 靜態方法 staticmethod 和 類方法 classmethod

輸出:

Python 靜態方法 staticmethod 和 類方法 classmethod

上面定義了一個類 Person,構造函數 __init__ 接收一個參數 name。

我們實例化了類 Person('alex'),name 賦值為 alex。然後用實例化的對象 a 調用實例方法 hello,hello 方法的第一個參數 self就是對象 a 的引用,就可以獲取到 name 的值 alex。

類方法 @classmethod


類方法不和特定的對象相關,只是和類有關。

請看如下的例子:

Python 靜態方法 staticmethod 和 類方法 classmethod

輸出:

Python 靜態方法 staticmethod 和 類方法 classmethod

上例中,我們定義了 Person 類,每次實例化時,執行構造函數,類的屬性 inst_num 加 1,調用了兩次 Person(),最終打印結果 2。

可以定義一個類方法,類方法的第一個參數是類的引用。下面是改造後的例子:

Python 靜態方法 staticmethod 和 類方法 classmethod

輸出:

Python 靜態方法 staticmethod 和 類方法 classmethod

上面定義了類方法 get_inst_num,使用裝飾器 @classmethod 裝飾。第一個參數我們打印出來了,就是 <class> 這個參數就是類 Person 的引用,它可以訪問類屬性 inst_num。/<class>

使用 @classmethod 的另一個好處是,我們用實例對象調用這個方法,第一個參數還是類引用。

Python 靜態方法 staticmethod 和 類方法 classmethod

輸出:

Python 靜態方法 staticmethod 和 類方法 classmethod

實例對象 a 和使用類 Person 調用方法 get_inst_num 輸出結果是一樣的。

靜態方法 @staticmethod


有時候,類中的方法和類自身或者它的實例沒有任何聯繫。它可能訪問一個全局的環境變量,或者其他類的某個屬性。這個時候,可以用靜態方法 @staticmethod。

Python 靜態方法 staticmethod 和 類方法 classmethod

輸出:

Python 靜態方法 staticmethod 和 類方法 classmethod

這裡使用靜態方法 debugon,我們在它定義上方使用 @staticmethod 裝飾器裝飾。

它訪問全局變量 DEBUG_PERSON,返回布爾類型,提示是否打開調試。如果打開調試,就在調用 hello() 方法的時候打印調試信息。

靜態方法可以由 self 調用。


分享到:


相關文章: