Decorator question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Steven W. Orr

    #1

    Decorator question

    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
  • Peter Otten

    #2
    Re: Decorator question

    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

    Comment

    Working...