python - 在python中使用装饰器时出现位置参数错误

标签 python decorator python-decorators

我在 python 中定义了一个装饰器函数,但在使用它时出现位置参数错误。这是我的代码:

def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper


@my_upper_case
def print_name(name):
    return name


if __name__ == "__main__":
    print(print_name("zeinab"))

返回的错误是:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)

我尝试用 python 2.7 和 python 3.6 运行代码。两者都返回了确切的错误。

最佳答案

如错误所述,您的包装函数不接受任何参数。它需要接受与它包装的函数相同的参数。

def wrapper(arg):
    return func(arg).upper()

关于python - 在python中使用装饰器时出现位置参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56314885/

相关文章:

python - 从 Python 3.6 中的嵌套字典过滤所需的值

c# - 如何在C#中自动生成装饰器模式

java - 违反is-a关系的装饰器设计模式

python - flask : Decorator to test query string arguments

python - 毕竟,在 Linux 上设置 Tensorflow 的正确方法是什么?

python - 当需要包含非 python 文件时,使用 PyInstaller 创建单个 exe?

python - 使用 urllib2 添加 SSL CA 文件

python - 如何从函数中动态删除装饰器?

python 包装器函数在装饰器中接受参数

python - Python 中经过验证的函数参数