谁能告诉我如何将参数传递给装饰器调用函数?
def doubleIt(Onefunc): def doubleIn(): return Onefunc()*Onefunc() return doubleIn @doubleIt def Onefunc(): return 5 print(Onefunc()) # it prints out 25.
但是,当我尝试升级Onefunc()
到:
@doubleIt def Onefunc(x): return x
我面临以下错误:
TypeError Traceback (most recent call last)in () 9 10 ---> 11 print(Onefunc(5)) 12 TypeError: doubleIn() takes 0 positional arguments but 1 was given
错误是自我解释,但我不知道如何更新doubleIn()
函数来处理它.
您需要传入可选的位置和关键字参数.
from functools import wraps def doubleIt(Onefunc): @wraps(Onefunc) def doubleIn(*args, **kwargs): return Onefunc(*args, **kwargs) * Onefunc(*args, **kwargs) return doubleIn @doubleIt def Onefunc(x): return x print(Onefunc(5))