Dynamically assigning function implementation in Python
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.namedef doItBetter(self): print "%s got it done better" % self.nameDoer.doSomething = doItBetter
Anonymous functions have nothing to do with this (by the way, Python supports simple anonymous functions consisting of single expressions, see lambda
).
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 MethodTypedoer.doSomething = MethodType(doItBetter, doer)