modifying method behaviour

Greg Krohn ask at me.com
Tue Aug 26 04:39:28 CEST 2003


"Craig Zoretich" <czoretich at octigabay.com> wrote in message
news:e7d0b08f.0308251612.cf5c9bd at posting.google.com...
> > 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)

I changed a couple of things, so this seems to work:

class Logger:
    def  __init__(self, func):
        self.func = func
    def __call__(self, *args):
        print "Called: %s with args %s" % (self.func.func_name, args)
        #Got rid of that 'self' all together
        return self.func(*args)

class MyClass:
    def __init__(self):
        #Created the logged method in the class's __init__
        self.myFunc = Logger(self.myFunc)

    def myFunc(self, a):
        return a

if __name__ == "__main__":
    m = MyClass()
    print m.myFunc('Testing...')


HTH,
greg






More information about the Python-list mailing list