[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

refer to self in a decorator on a class method

refer to self in a decorator on a class method

pieter.cogghe@gmail.com

3/29/2010 9:39:00 AM

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?

thanks a lot,

pieter

Peter Otten

3/29/2010 9:54:00 AM

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

Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
refer to self in a decorator on a class method

Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te

Il servizio è completamente GRATUITO!