Dynamically add member function to an instance of a class in Python

For Python 2.X you can use:

import types
class C:
    pass

def f(self):
    print self

a = C()
a.f = types.MethodType(f,a)
a.f()

For Python 3.X:

import types
class C(object):
    pass

def f(self):
    print(self)

a = C()
a.f = types.MethodType(f,a)
a.f()

You should put f in the class, not in the instance...

 class C:
     pass

 def f(self):
    print(self)

 a = C()
 C.f = f
 a.f()

For the interpreter myObject.foo() is the same as myClass.foo(myObject) when the object doesn't hold anything named foo, but a function placed inside a object is just a function.

Tags:

Python