modifying method behaviour

Craig Zoretich czoretich at octigabay.com
Mon Aug 25 20:12:47 EDT 2003


Hi,

I am trying to modify the behaviour of a method so it will
automatically log information for me.  I have been able to do this
with functions by using the code that was kindly submitted to this
newsgroup:

> class logger:
>     def  __init__(self, func):
>          self.func = func
>     def __call__(self, *args):
>         print "Called: %s with args %s" % (self.func.func_name, args)
>         return self.func(*args)
> 
> def myfunc(a): return a
> 
> myfunc = logger(myfunc)

This code works great for functions, but it doesn't work too well for
methods within a class.  Here's an example of my code:

> class logger:
>     def  __init__(self, func):
>          self.func = func
>     def __call__(self, *args):
>         print "Called: %s with args %s" % (self.func.func_name, args)
>         return self.func(self, *args)
> 
> class myClass:
>     def myfunc(self, a): return a
> 
>     myfunc = logger(myfunc)

What happens is that the "self" argument in myClass.myfunc is being
filled with an instance of the logger class, so it doesn't see any of
the attributes of "myClass".   Is there a simple way of tweeking this
code, or do I need to redesign how I am doing this?

Thanks in advance,
Craig




More information about the Python-list mailing list