-2

我是一名自学成才的程序员,在 python 中的 @decorator 上需要你的帮助。

这是我的问题。在我用装饰器运行 other(multiply) 之后,它出现了一个错误: wrap_func() 接受 0 个位置参数,但给出了 1 个。我不知道为什么以及如何解决这个问题。我的主要目的是学习装饰器是如何工作的;因此下面的代码可能没有意义。

def multiply(a,b):
    return a*b
###pass in multiply function in other()

def other(multiply):
    print('passed in')
    print(multiply(1,2))

other(multiply)
### result shows passed in and 2, as expected

### Set up decorator func here
def decorator_prac(old_func):

    def wrap_func():
        multiply(1,2)
        old_func()
        print(1+7)
    return wrap_func

###add decorator on def other(multiply)
@decorator_prac
def other(multiply):
    print('what should I say')
    print(multiply(1,2))

###Run other(multiply)
other(multiply)

输出:

passed in
2
Traceback (most recent call last):
  File "so.py", line 28, in <module>
    other(multiply)
TypeError: wrap_func() takes 0 positional arguments but 1 was given
4

2 回答 2

0

您传递的功能与使用它的方式之间存在差异。这是跟踪和解决方案。我仔细检查了装饰器看到的函数,然后添加了所需的参数。如果您需要它是通用的,您将需要一个通用参数列表,例如*args.

### Set up decorator func here
def decorator_prac(old_func):
#def decorator_prac(old_func):
    print("decorator arg", old_func)    # Track what is passed in

    def wrap_func(func_arg):            # Accommodate the function profile
        multiply(1,2)
        old_func(func_arg)              # Implement the proper profile
        print(1+7)
    return wrap_func

输出:

passed in
2
decorator arg <function other at 0x7f0e7b21b378>
what should I say
2
8
于 2018-09-26T16:38:45.887 回答
0

装饰器接受一个函数对象(这里:other(multiply))并返回另一个wrap_func()替换它的函数。该名称other现在指的是被替换的函数。

虽然原始函数有一个参数,但替换函数没有。使用参数调用无参数函数以所示方式失败。

于 2018-09-26T16:39:05.770 回答