首页 > 解决方案 > 装饰器无法识别功能

问题描述

我一直在使用 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'

标签: python

解决方案


首先,有一些关于 SO 的问题可以处理这个问题。在编写新问题之前,您应该对此错误进行更多研究。但不管怎么说:

错误的原因是因为您通过在 a 之前编写def装饰器来调用装饰器,因为您已经使用方括号调用它decorator()而没有传入任何内容,它会引发错误。

对于您的装饰器,正确的用法是:

@decorator # no brackets here
def function()
    ...

推荐阅读