By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Decorator question

P: n/a
I just discovered decorators. Very cool. My question is that I can't
figure out how to make a decorator not be restricted to a function so it
would also work on a method.

Here's my code:

def g(expr):
def rpt(func):
def wrapper(t):
for ii in range(expr):
print ii,
func(t)
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
return func
return wrapper
return rpt

@g(20)
def f(s):
print 's="%s"'%s
f('Hello')

It works fine, but now I want to apply the same decorator to a class
method.

class KK:
# @g(20) This obviously doesn't work.
def f(self, s):
print 's= %s'%s

k = KK()
k.f('Hello')

Is there a trick I need?

TIA

--
Time flies like the wind. Fruit flies like a banana. Stranger things have .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
May 23 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Steven W. Orr wrote:
I just discovered decorators. Very cool. My question is that I can't
figure out how to make a decorator not be restricted to a function so it
would also work on a method.

Here's my code:
@g(20)
def f(s):
print 's="%s"'%s
f('Hello')
Here you are calling f() with one string argument.
It works fine, but now I want to apply the same decorator to a class
method.

class KK:
# @g(20) This obviously doesn't work.
def f(self, s):
print 's= %s'%s

k = KK()
k.f('Hello')
Here you are calling KK.f() with two arguments (an implicit KK instance and
the explicit "Hello" string).

Both calls are channeled through wrapper(t) which expects exactly one
parameter.
Is there a trick I need?
Change wrapper() to accept an arbitrary number of arguments:
def g(expr):
def rpt(func):
def wrapper(*args):
for ii in range(expr):
print ii,
func(*args)
wrapper.__name__ = func.__name__
wrapper.__dict__ = func.__dict__
wrapper.__doc__ = func.__doc__
return func
return wrapper
return rpt
Peter

May 23 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.