Pythonでクラスのクラスメソッドを動的に作成するにはどうすればいいですか?[重複] 質問する

Pythonでクラスのクラスメソッドを動的に作成するにはどうすればいいですか?[重複] 質問する

小さなPythonプログラムを次のように定義すると

class a():
    def _func(self):
        return "asdf"

    # Not sure what to resplace __init__ with so that a.func will return asdf
    def __init__(self, *args, **kwargs):
         setattr(self, 'func', classmethod(self._func))

if __name__ == "__main__":
    a.func

トレースバックエラーが発生します

Traceback (most recent call last):
  File "setattr_static.py", line 9, in <module>
    a.func
AttributeError: class a has no attribute 'func'

私が理解しようとしているのは、オブジェクトをインスタンス化せずにクラスメソッドをクラスに動的に設定するにはどうすればよいかということです。


編集:

この問題の答えは

class a():
    pass

def func(cls, some_other_argument):
    return some_other_argument

setattr(a, 'func', classmethod(func))

if __name__ == "__main__":
    print(a.func)
    print(a.func("asdf"))

次の出力を返します

<bound method type.func of <class '__main__.a'>>
asdf

ベストアンサー1

クラス オブジェクトへの単純な割り当て、またはクラス オブジェクトでの setattr によって、クラスにクラスメソッドを動的に追加できます。ここでは、混乱を減らすために、クラスを大文字で始めるという Python の規則を使用しています。

# define a class object (your class may be more complicated than this...)
class A(object):
    pass

# a class method takes the class object as its first variable
def func(cls):
    print 'I am a class method'

# you can just add it to the class if you already know the name you want to use
A.func = classmethod(func)

# or you can auto-generate the name and set it this way
the_name = 'other_func' 
setattr(A, the_name, classmethod(func))

おすすめ記事