Chaning instance methods

Hans Nowak ivnowa at hvision.nl
Wed Apr 7 02:26:21 EDT 1999


On 6 Apr 99, Ce'Nedra took her magical amulet and heard Jody Winston say:

>I don't understand how to change instance methods.  For example:
>
>class Foo:
>	def __init__(self):
>		self.data = 42
>	def m(self):
>		print "Foo.m"
>		print dir(self)
>
>def m2(self):
>	print "m2"
>	print dir(self)
>
>f = Foo()
>f.m()
># this fails
># f.m = m2
># f.m()

I'm not sure, but I think it works like this... Foo.m and f.m are somehow 
related to Foo or its instances... they're methods; m2, however, is just a 
function. When you do something like 'f.m = m2' you attach a plain old 
function to a class instance. Python apparently does not like this; 'f.m()' 
won't work anymore, since the language does not do an automatic conversion 
from function to method (although they look the same!). 

To call such a function, you could do

f.m = m2
f.m(f)		# need to provide 'self' explicitly

which is probably not what you want.

To be honest, I don't really have a good solution to this. Anybody else?

>Foo.m = m2 # Changes all instances of Foo.m
>f.m()

This works because m2 is "injected" though Foo, and thus accepted as a 
method. Try to print Foo.m; it'll say "unbound method". And printing f.m will 
show that m2 is accepted as a method in f, too. :^S

>f2 = Foo()
>f2.m()

Veel liefs,

+  Hans Nowak  (Zephyr Falcon)
+  Homepage (under construction): http://www.cuci.nl/~hnowak/
+  You call me a masterless man. You are wrong. I am my own master.
+  May an orc cheat on your fiance with your life!




More information about the Python-list mailing list