1. 程式人生 > 實用技巧 >python內建裝飾器---- staticmethod和classmethod

python內建裝飾器---- staticmethod和classmethod

staticmethod

staticmethod 只能作為函式裝飾器應用。其作用為將一個函式轉換為靜態方法。下面一段程式碼中,若不在def get(argv1)上新增裝飾器staticmethod.
在執行程式碼test.get("hello") 將會出現 TypeError: get() takes 1 positional argument but 2 were given。
這說明 在不新增裝飾器staticmethod,Python 直譯器僅僅將def get(argv1) 解釋為類C 內部定義的函式;新增後,則將其解釋為類C 的靜態方法。

class C:
    def __init__(self):
        self._item = 1
    
    @staticmethod
    def get(argv1):
        # print(self._item)
        print(argv1)

test = C()
test.get('hello')
C.get('hello')

classmethod

classmethod,與staticmethod類似, 只能作為函式裝飾器應用。其作用為將一個函式轉換為類方法。若不在def get(argv1)上新增裝飾器classmethod.
在執行程式碼時 C.get('hello')將會出現 TypeError: get() missing 1 required positional argument: 'argv1' 。
這說明 在不新增裝飾器classmethod,Python 直譯器不會講C作為cls 傳輸給 get(cls,argv) 。

class C:
    def __init__(self):
        self._item = 1
   
    @classmethod
    def get(cls, argv1):
        # print(self._item)
        print(argv1)
test = C()
test.get('hello')
C.get('hello')

小結

staticmethod classmethod
區別 講func 裝換為靜態方法 將func 轉換為類方法
相似點 呼叫方式相同