Dynamically assigning function implementation in Python
yak's answer works great if you want to change something for every instance of a class.
If you want to change the method only for a particular instance of the object, and not for the entire class, you'd need to use the MethodType
type constructor to create a bound method:
from types import MethodType
doer.doSomething = MethodType(doItBetter, doer)
Your first approach was OK, you just have to assign the function to the class:
class Doer(object):
def __init__(self):
self.name = "Bob"
def doSomething(self):
print "%s got it done" % self.name
def doItBetter(self):
print "%s got it done better" % self.name
Doer.doSomething = doItBetter
Anonymous functions have nothing to do with this (by the way, Python supports simple anonymous functions consisting of single expressions, see lambda
).