Python classmethod 修飾子
説明
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 組み込み関数