如何在python中为一个类动态创建类方法

问题描述:

如果我定义一个小的python程序为

If I define a little python program as

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'

我想要弄清楚的是,我怎么能动态设置一个类方法而不实例化一个对象?

What I am trying to figure out is, how can I dynamically set a class method to a class without instantiating an object?

这个问题的答案是

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


可以动态添加类方法通过类对象的简单赋值或通过类对象的setattr赋值给类。这里我使用python约定,类以大写字母开头,以减少混淆:

You can dynamically add a classmethod to a class by simple assignment to the class object or by setattr on the class object. Here I'm using the python convention that classes start with capital letters to reduce confusion:

# 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))