Add bound methods to instantiated objects in Python
In Python, as in other dynamic languages, you can add new methods to a class after it's been defined. To do this in Python, you define a function that takes self as its first parameter, then assign that function to an attribute of the class:
class C(object):
pass # No methods... yet
def foo(self):
print self
C.foo = foo
When executing the final line, Python automagically wraps the function foo in an unbound method called foo, and assigns the unbound method to C.foo. (You need to be aware of this if you ever try to assign a function to an attribute of a class and want to use it as just a function: in that case, you would need to put it inside a data structure instead or use C.foo.im_func to get at the original function.)
This principle is not at work when you are dealing with an instance of a class. If you assign a function to an attribute of an instance, it will not be converted into anything. The creation of a bound method must be done explicitly, like this:
import types
instance = C()
instance.bar = types.MethodType(foo, instance, instance.__class__)
In this example, invoking MethodType creates a new bound method object. Its parameters are a function, the instance to which the method should be bound, and the class (the last parameter could simply be C, but using instance.__class__ allows you to use this approach when you don't have a direct reference to the class.)
Tweet it!
Comments
instance.bar = foo.__get__(instance, instance.__class__)
I recommend to read [Link to www.cafepy.com] There is awesome info about python type system internals.