Decorating class member functions

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu May 3 23:50:19 EDT 2007


On Thu, 03 May 2007 19:28:52 -0700, Andy Terrel wrote:

> I just need to keep the state around. I make a call to some function
> that is pretty expensive so I want to save it as a member during the
> __init__ of the decorator.
> 
> Yeah I'm afraid it can't be done either, that's why I asked the group.

You can do it if you give up on using the decorator syntax.

(Now that I've said that, some clever bunny will show me how to do it.)

def make_decorator(n):
    def addspam(fn):
        def new(*args):
            print "spam " * n
            return fn(*args)
        return new
    return addspam


class Parrot(object):
    def __init__(self, count=3):
        from new import instancemethod as im
        self.describe = im(make_decorator(count)(self.__class__.describe), self)
    def describe(self):
        return "It has beautiful plummage."


>>> bird = Parrot()
>>> bird.describe()
spam spam spam
'It has beautiful plummage.'
>>> 
>>> 
>>> bird = Parrot(5)
>>> bird.describe()
spam spam spam spam spam
'It has beautiful plummage.'



-- 
Steven D'Aprano 




More information about the Python-list mailing list