我一直在使用Flask.route() decorator一段时间,并想编写自己的decorator,但它总是告诉我该函数没有传递给它。
我已经完全复制了Flask示例中的所有内容,所以我的decorator定义一定是错误的:
def decorator(f, *d_args):
def function(*args, **kwargs):
print('I am decorated')
return f(*args, **kwargs)
return function
@decorator()
def test(a, b=1):
print('Test', a, b)
test(1, 6)
我得到的错误:
Traceback (most recent call last):
File "C:/Users/Tobi/Desktop/decorators.py", line 49, in <module>
@decorator()
TypeError: decorator() missing 1 required positional argument: 'f'
首先,有一些问题是关于如何处理这个问题的。在写新问题之前,你应该对这个错误做更多的研究。总之:
你的错误的原因是因为你调用装饰器写在def
之前,因为你已经使用括号decorator()
调用它而没有传递任何东西,它抛出一个错误。
@decorator # no brackets here
def function()
...