Python classmethod 修飾符

Python 內置函數 Python 內置函數


描述

classmethod 修飾符對應的函數不需要實例化,不需要 self 參數,但第一個參數需要是表示自身類的 cls 參數,可以來調用類的屬性,類的方法,實例化對象等。

語法

classmethod 語法:

classmethod

參數

  • 無。

返回值

返回函數的類方法。

實例

以下實例展示了 classmethod 的使用方法:

#!/usr/bin/python # -*- coding: UTF-8 -*- class A(object): bar = 1 def func1(self): print ('foo') @classmethod def func2(cls): print ('func2') print (cls.bar) cls().func1() # 調用 foo 方法 A.func2() # 不需要實例化

輸出結果為:

func2
1
foo

Python 內置函數 Python 內置函數