Python Class Based Decorator with parameters that can decorate a method or a function

后端 未结 3 1016
南笙
南笙 2020-12-07 22:51

I\'ve seen many examples of Python decorators that are:

  • function style decorators (wrapping a function)
  • class style decorators (implementing __i
3条回答
  •  广开言路
    2020-12-07 23:10

    In your list of types of decorators, you missed decorators that may or may not take arguments. I think this example covers all your types except "function style decorators (wrapping a function)"

    class MyDecorator(object):
    
        def __init__(self, argument):
            if hasattr('argument', '__call__'):
                self.fn = argument
                self.argument = 'default foo baby'
            else:
                self.argument = argument
    
        def __get__(self, obj, type=None):
            return functools.partial(self, obj)
    
        def __call__(self, *args, **kwargs):
            if not hasattr(self, 'fn'):
                self.fn = args[0]
                return self
            print "In my decorator before call, with arg %s" % self.argument
            self.fn(*args, **kwargs)
            print "In my decorator after call, with arg %s" % self.argument
    
    
    class Foo(object):
        @MyDecorator("foo baby!")
        def bar(self):
            print "in bar!"
    
    class Bar(object):
        @MyDecorator
        def bar(self):
            print "in bar!"
    
    @MyDecorator
    def add(a, b):
        print a + b
    

提交回复
热议问题