Decorating instance methods

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 9 04:01:15 EDT 2007


Alexander Draeger <dral at informatik.tu-chemnitz.de> wrote:

> Hello everybody,
> 
> I'm very interesting in using the decorator concept, but I can't
> convert it in useful things. I have read many about decorators and
> have seen a lot of examples, but I search a possibility, to decorate
> methods of classes with reference to the instances. For example:
> 
> I have a class A:
> 
> class A(object):
>     def __init__(self, name):
>         self.name=name
> 
>     @logging
>     def hello(self, name):
>         print 'Hello World.'
> 
> 
> 
> >>>a=A('Ernie')
> >>>b=A('Bert')
> >>>a.hello()
> Entering a method. [Ernie]
> Hello World.
> 
> >>>b.hello()
> Entering a method. [Bert]
> Hello World.
> 
> 
> How should I implement the function logging, when I want to use the
> variable self.name for the logging message?
> 

(Did you intend that other parameter to the hello method? If so you had 
better pass it in when you call the method.)

Try this:

>>> def logging(f):
	def deco(self, *args, **kw):
		print "Entering a method [%s]" % self.name
		return f(self, *args, **kw)
	return deco

>>> class A(object):
    def __init__(self, name):
        self.name=name

    @logging
    def hello(self, name):
        print 'Hello World.'

        
>>> a=A('Ernie')
>>> a.hello('world')
Entering a method [Ernie]
Hello World.



More information about the Python-list mailing list