从Python 2.6开始,您应该使用
types模块的
MethodType类:
from types import MethodTypeclass A(object): def m(self): print 'aaa'a = A()def new_m(self): print 'bbb'a.m = MethodType(new_m, a)
但是,正如另一个答案指出的那样,这对于新型类的“魔术”方法(例如)无效
__str__()。

从Python 2.6开始,您应该使用
types模块的
MethodType类:
from types import MethodTypeclass A(object): def m(self): print 'aaa'a = A()def new_m(self): print 'bbb'a.m = MethodType(new_m, a)
但是,正如另一个答案指出的那样,这对于新型类的“魔术”方法(例如)无效
__str__()。