Decorators using instance variables

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Aug 26 16:36:45 EDT 2008


robert2821 a écrit :
> 
> Hi,
> 
> I'm new; greetings all!

Hello.

Since you're new here, first a couple advises:
1/ the python mailing list is relayed to the comp.lang.python usenet 
newsgroup (from where I'm reading your post and answering it), so please 
avoid attachments. Either put the full code in your post, or provide an 
url to somewhere we can read it.
2/ don't bother reading anything from someone named 'castironpi', it's 
one of our currently active resident troll, and he is worse than clueless.

> I'm wondering if the following program should work.  I think it should 
> print 'Hello, World', but instead it produces a TypeError.  Is this a 
> bug in decorators, a feature of them, or a mistake or misunderstanding 
> on my part?

I doubt this is a bug. But it can be both a feature and a mistake or 
misunderstanding !-)

<ot topic="your code">
Please read pep08. Coding convention are very strong in Python. And 
preferably, use spaces (4 spaces per tab) for indentation.
http://www.python.org/dev/peps/pep-0008/
</ot>


> def getdec(f):
>    dec = decorator(f)
>    return dec. docall
> 
> class decorator: 

<ot>
- pep08 : class names should be CamelCased
- unless you have a compelling reason to stick to a by now antiquated 
object model, better to use "new-style" classes. Part of what you'll 
read here about Python's OO features apply only to new-style classes, 
and most of the remaining apply to both object models.

IOW, make this:

class Decorator(object):
</ot>

>    def __init__ (self, f):
>        self.f = f
> 
>    def docall (self, *a):
>        return self.f(*a)

<ot>
You can write your own callable types by implementing the __call__ method.
</ot>

> class test:
>    @getdec
>    def doit (self, message):
>        print message
> 
> if __name__ == '__main__':
>    foo = test ()
>    foo.doit ('Hello, world')
> 



More information about the Python-list mailing list