【发布时间】:2019-03-25 07:35:54
【问题描述】:
假设我有这个装饰器:
def decorator_with_args(decorator_arg1, decorator_arg2):
def decorator(func):
def wrapped(*args, **kwargs):
if decorator_arg1 == 'arg1' and decorator_arg2 == 'arg2':
return func(*args, **kwargs)
return wrapped
return decorator
通常你会像这样装饰一个函数:
@decorator_with_args('arg1', 'arg2')
def function():
return 'foo'
>>> foo = function()
'foo'
如何在不使用@ 语法的情况下调用它?
我知道,如果它只是一个单层装饰器(即没有 args 的装饰器),那么你调用它的方式就是将它包装在装饰器函数中,如下所示:
>>> foo = decorator(function)
'foo'
注意function 没有被调用。如果装饰器和函数都有需要传递的参数,这将如何工作?
>>> foo = decorator_with_args(decorator(wrapped_function))
但是那么装饰器的*args和**kwargs和原来的函数去哪里了呢?
【问题讨论】:
-
这毫无意义。
decorator在decorator_with_args之外不存在。 -
foo = decorator_with_args('arg1', 'arg2)(function)() -
@Aran-Fey 抱歉,我的意思是假设性的。
标签: python python-3.x decorator wrapper