【问题标题】:Python, a decorator as an argumentPython,作为参数的装饰器
【发布时间】:2018-03-05 10:16:52
【问题描述】:

我想做一个装饰器,它将另一个装饰器函数作为参数。

装饰器会做额外的工作。

def raise_error(func):
    def wrapper(*args, **kwargs):
        print('hello from decorator')
        return func(*args, **kwargs)
    return wrapper


@raise_error
def hello():
    return 'Hellom from function'


print(hello())

从技术上讲,我可以在 raise_error 装饰器中编写一个将采用 raise_error 装饰器的装饰器并做一些额外的流程?

提前谢谢你。

【问题讨论】:

    标签: python python-3.x decorator


    【解决方案1】:

    另一种可能将 func 作为装饰器的参数。

    def raise_error(func):
        def wrapper(*args, **kwargs):
            test_func = getattr(func, 'tester', None)
            test_func()
            print('Hello from decorator')
            return func(*args, **kwargs)
        return wrapper
    
    
    def test():
        print('Hello from test')
    
    
    def hello():
        print('Hello from function')
        return 'Hello from function'
    hello.tester = test
    
    
    decorated_hello = raise_error(hello)
    decorated_hello()
    

    结果:

    Hello from test
    Hello from decorator
    Hello from function
    

    【讨论】:

    • 谢谢,这正是我要找的!
    【解决方案2】:

    你说的是多个装饰器吗?

    像这样

    def raise_error(func):
        def wrapper(*args, **kwargs):
            print('hello from decorator')
            return func(*args, **kwargs)
        return wrapper
    
    
    def foo(func):
        def wrapper(*args, **kwargs):
            print('bar')
            return func(*args, **kwargs)
        return wrapper
    
    
    @foo
    @raise_error
    def hello():
        return 'Hello from function'
    
    
    print(hello())
    

    相关问题:How to make a chain of function decorators?

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 2011-11-21
      • 1970-01-01
      • 2021-11-26
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2016-09-27
      • 2023-03-26
      相关资源
      最近更新 更多