From: Alan L. <al...@li...> - 2002-06-24 04:25:55
|
This is probably more of a Python question but here goes: I want to write a class whose methods with 'self modifying' code in the following sense: I want to transparently replace calls to a method foo(...) by a call to foobar(...). The following would appear to do the trick: class A: def __getattr__(self, name): return A.__dict__[name + 'bar'] def foobar(self): print "calling foobar()" lets try it out: bin>jython -i test.py >>> a = A() >>> a.foo # looks good <function foobar at 130947> >>> a.foo() Traceback (innermost last): File "<console>", line 1, in ? TypeError: foobar() takes at least 1 argument (0 given) # oops -- seems I have to pass in the 'self' explicitly ?? >>> a.foo(a) calling foobar() >>> # What gives ... lets look at foobar: >>> a.foobar <method A.foobar of A instance at 2862744> >>> # -- foobar is a method when looked up directly but not when looked up using the getattr detour ! Why is this ? I thought the fact I was grabbing the call to lookup foo and making it look up foobar instead would be transparent to the underlying implementation code that is handling the 'method aspect' of the function call (i.e. the bit that takes the function and pops the 'self' parameter in as the first arg). Put another way isn't a.foobar the the same as a.__class__.__dict__['foobar'] which is the same as A.__dict__['foobar'] ?? If such is not the case how can I implement the functionality I want (and yes, I do need i done transparently like this becuase the mapping is actually very dynamic - don't ask why ......). I get the same (counter intutitve, at least to me) behaviour in Python (2.1) so clearly the fault lies with me I guess, but I really don't see it. Is there madness in the method ?? Tnx Alanl ----- Alan Littleford al...@li... (650)-255-6909 |