Is it possible to change an instance’s method implementation without changing all other instances of the same class? [duplicate]

Since Python 2.6, you should use the types module’s MethodType class:

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)

As another answer pointed out, however, this will not work for ‘magic’ methods of new-style classes, such as __str__().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)