python change function of object 1

python change function of object

from types import MethodType

class A(object):
    def m(self):
        print 'aaa'

a = A()

def new_m(self):
    print 'bbb'

a.m = MethodType(new_m, a)

Here is what the above code is Doing:
1. Create a class A.
2. Create an instance of A.
3. Define a function new_m.
4. Bind new_m to the instance a.
5. Call the new method.

Similar Posts