replace a method in class: how?

John Machin sjmachin at lexicon.net
Mon Jun 26 19:39:10 EDT 2006


On 27/06/2006 9:14 AM, Brian Blais wrote:
> 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
> 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?
> 

You have a strange definition of "obvious". You say you want to replace 
a method in a *class*, not in an instance of that class ... so just do that:

|>> class This(object):
...      def update(self,val):
...          print val
...
|>> def another_update(obj,val):
...      print "another",val
...
|>> This.update = another_update
|>> t = This()
|>> t.update(42)
another 42

Cheers,
John



More information about the Python-list mailing list