I found really good example how to add new method to the class dynamically (transplant class):
def say(host, msg):
print '%s says %s' % (host.name, msg)
def funcToMethod(func, clas, method_name=None):
setattr(clas, method_name or func.__name__, func)
class transplant:
def __init__(self, method, host, method_name=None):
self.host = host
self.method = method
setattr(host, method_name or method.__name__, self)
def __call__(self, *args, **kwargs):
nargs = [self.host]
nargs.extend(args)
return apply(self.method, nargs, kwargs)
class Patient:
def __init__(self, name):
self.name = name
if __name__ == '__main__':
jimmy = Patient('Jimmy')
transplant(say, jimmy, 'say1')
funcToMethod(say, jimmy, 'say2')
jimmy.say1('Hello')
jimmy.say2(jimmy, 'Good Bye!')
But I don’t understand, how to modify it for adding static methods. Can someone help me?
All you need to do is wrap the function in a
staticmethod()call:or apply it as a decorator to the function definition:
which comes down to the same thing.
Just remember; the
@decoratorsyntax is just syntactic sugar for writingtarget = decorator(target), wheretargetis the decorated object.