简体   繁体   中英

What is the correct way to define a python decorator in a class?

What I'd like to achieve is that the following code out puts the following:

  • Here1
  • Here2
  • Here3 argOne argTwo

I'm wondering if my use of __call__ is somehow clobbering functools.wraps; it also appears that the arguments are lost at some point.

Is what I'm trying to achieve possible?

from functools import wraps

class Decorator():

    def __init(self, something=None):
            self.something = something

    def __call__(self, func):
            print 'Here1'
            @wraps(func)
            def _wrapper(*args, **kwargs):
                return self.call(func, *args, **kwargs)
            return _wrapper

    def call(self, func, *args, **kwargs):
            print 'Here2'
            retsult = func(*args, **kwargs)
            return result


if __name__ == '__main__':

    decorator = Decorator()

    @decorator
    def do_the_thing(arg1='argOne', arg2='argTwo'):
            print 'Here3 {0} {1}'.format(arg1, arg2)
            return

Seems you just had a few typos and weren't actually calling the function do_the_thing .

Changed it to this and worked just fine.

from functools import wraps


class Decorator():

    def __init__(self, something=None): # you are missing the __ on the right
            self.something = something

    def __call__(self, func):
            print 'Here1'
            @wraps(func)
            def _wrapper(*args, **kwargs):
                return self.call(func, *args, **kwargs)
            return _wrapper

    def call(self, func, *args, **kwargs):
            print 'Here2'
            result = func(*args, **kwargs) # result was misspelled
            return result


if __name__ == '__main__':

    @Decorator() # Just a bit cleaner
    def do_the_thing(arg1='argOne', arg2='argTwo'):
            print 'Here3 {0} {1}'.format(arg1, arg2)

    do_the_thing() # func was never called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM