How can I dynamically create class methods for a class in python [duplicate]

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

Leave a Comment