python中的装饰器查询

我是一名自学成才的程序员,需要你在 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


蝴蝶刀刀
浏览 166回答 2
2回答

DIEA

装饰器接受一个函数对象(这里是:)other(multiply)并返回另一个wrap_func()替换它的函数。该名称other现在指代替换的函数。虽然原始函数接受一个参数,但替换函数没有。以所示方式调用带参数的无参数函数失败。

www说

您传递的函数与使用它的方式之间存在差异。这是跟踪和解决方案。我仔细检查了装饰器看到的函数,然后添加了所需的参数。如果您需要这是通用的,则需要一个通用参数列表,例如*args.### Set up decorator func heredef decorator_prac(old_func):#def decorator_prac(old_func):&nbsp; &nbsp; print("decorator arg", old_func)&nbsp; &nbsp; # Track what is passed in&nbsp; &nbsp; def wrap_func(func_arg):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Accommodate the function profile&nbsp; &nbsp; &nbsp; &nbsp; multiply(1,2)&nbsp; &nbsp; &nbsp; &nbsp; old_func(func_arg)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # Implement the proper profile&nbsp; &nbsp; &nbsp; &nbsp; print(1+7)&nbsp; &nbsp; return wrap_func输出:passed in2decorator arg <function other at 0x7f0e7b21b378>what should I say28
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python