python - 装饰器无法识别功能
问题描述
我一直在使用 Flask.route() 装饰器并想编写自己的装饰器,但它总是告诉我该函数没有传递给它。
我已经完全复制了 Flask 示例中的所有内容,所以我的装饰器定义一定是错误的:
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'
解决方案
首先,有一些关于 SO 的问题可以处理这个问题。在编写新问题之前,您应该对此错误进行更多研究。但不管怎么说:
错误的原因是因为您通过在 a 之前编写def
装饰器来调用装饰器,因为您已经使用方括号调用它decorator()
而没有传入任何内容,它会引发错误。
对于您的装饰器,正确的用法是:
@decorator # no brackets here
def function()
...
推荐阅读
- javascript - Shift选项卡不保留元素焦点
- python - 如何将 3 个列表值与 If 条件进行比较
- c# - 为什么 xUnit 测试没有变成绿色?
- python - 使用 unittest 测试烧瓶应用程序时出错
- ruby - 使用 OptParser 在 Ruby 脚本中访问命令行选项文字
- r - 如果存在多行,则 R_exclude 具有包含值的列的行
- android - 运行从 android APK 编译的 ELF 二进制文件需要什么?(了解 android 内部结构)
- sql - 如何将 YYYYMM 转换/提取为年份和月份名称?Teradata SQL
- ibm-doors - 如何创建一个视图来显示单个项目下所有正式模块中的所有现有属性 DOORS?
- r - rtweet“search_tweets”函数不返回坐标