refer to self in a decorator on a class method
Peter Otten
__peter__ at web.de
Mon Mar 29 05:53:51 EDT 2010
Yuccaplant wrote:
> Hi all,
>
> I would like to do something like this:
>
> ********************
> class HelloWorld (object):
>
> def __init__(self,clk):
> self.clk = clk
>
> @always(self.clk.posedge)
> def sayHello(self):
> print "%s Hello World!" % now()
> ********************
>
> Problem is however I can't refer to self in the decorator call. Is
> there any workarround?
Pass attribute names:
>>> def always(name):
... def always(f):
... def wrapper(self, *args, **kw):
... print attrgetter(name)(self)
... return f(self, *args, **kw)
... return wrapper
... return always
...
>>> from operator import attrgetter
>>> class A(object):
... def __init__(self, clk):
... self.clk = clk
... @always("clk.posedge")
... def hello(self):
... print "hello world"
...
>>> class clk:
... posedge = 42
...
>>> A(clk).hello()
42
hello world
There may be better ways depending on your usecase.
Peter
More information about the Python-list
mailing list