replace a method in class: how?

Bruno Desthuilliers bdesth.quelquechose at
Tue Jun 27 05:05:30 CEST 2006

Brian Blais a écrit :
> Hello,
> I want to replace a method in a class during run-time with another 
> function.  I tried the obvious, but it didn't work:
> class This(object):
>     def update(self,val):
>         print val
> def another_update(obj,val):
>     print "another",val
> t=This()
> t.update(5)
> t.update=another_update

This is not "replacing a method in a class", but replacing it in an 

> t.update(5)  # this one doesn't work, gives
> # TypeError: another_update() takes exactly 2 arguments (1 given)

> clearly it isn't seeing it as a method, just an attribute which happens 
> to be a function.  Is there a preferred way to do this?

import types
t.update = types.MethodType(another_update)

More information about the Python-list mailing list