Instrospection question
Peter Otten
__peter__ at web.de
Fri Dec 21 06:34:15 EST 2007
Matias Surdi wrote:
> I have the following code:
>
> --------------------------
> import new
>
> class A:
> def a(self):
> print "Original"
>
> def other(cad):
> return cad + " modified"
>
> def replace_method(method):
> def b(self,*args,**kwargs):
> result = method(*args,**kwargs)
> return other(result)
> return b
>
>
> a = A()
>
> setattr(a,"a",new.instancemethod(replace_method(a.a) ,a,A))
>
> a.a()
>
> #Result should be:
> # Original modified
>
> ------------------------------
>
> As you can see, what I'm trying to do is "replace" a method with another
> one wich is the same method but with a function applied to it (in this
> case, a string concatenation ( +" modified"))
>
> Can anybody help me with this?
Change A.a() to return a value:
class A:
def a(self):
return "Original"
# ...
print a.a()
and it should work. You can then start to simplify:
class A:
def a(self):
return "Original"
def other(cad):
return cad + " modified"
def replace_method(method):
def b(*args,**kwargs):
result = method(*args,**kwargs)
return other(result)
return b
a = A()
a.a = replace_method(a.a)
print a.a()
Peter
More information about the Python-list
mailing list