【问题标题】:got positional argument error when using decorator in python在 python 中使用装饰器时出现位置参数错误
【发布时间】:2019-05-26 15:30:00
【问题描述】:

我在 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 运行代码。两者都返回了确切的错误。

【问题讨论】:

    标签: python decorator python-decorators


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      wrapper 包装了该函数,这意味着它将“在其位置起作用”。

      因此,如果您调用print_name("zeinab"),则将使用wrapper("zeinab") 调用包装器。

      wrapper 不接受 "zeinab" 参数,因为您没有给它任何参数。

      def my_upper_case(func):
      
          def wrapper(*args, **kwargs):
              return func(*args, **kwargs).upper()
      
          return wrapper
      
      
      @my_upper_case
      def print_name(name):
          return name
      
      
      if __name__ == "__main__":
          print(print_name("zeinab"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-30
        • 2019-01-02
        • 1970-01-01
        • 2019-02-24
        • 2018-09-24
        • 2019-10-20
        • 1970-01-01
        • 2021-02-22
        相关资源
        最近更新 更多