为了账号安全,请及时绑定邮箱和手机立即绑定

python中的装饰器查询

python中的装饰器查询

蝴蝶刀刀 2021-06-21 17:00:49
我是一名自学成才的程序员,需要你在 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 heredef 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_pracdef other(multiply):    print('what should I say')    print(multiply(1,2))###Run other(multiply)other(multiply)输出:passed in2Traceback (most recent call last):  File "so.py", line 28, in <module>    other(multiply)TypeError: wrap_func() takes 0 positional arguments but 1 was given
查看完整描述

2 回答

?
DIEA

TA贡献1820条经验 获得超2个赞

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

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


查看完整回答
反对 回复 2021-06-29
?
www说

TA贡献1775条经验 获得超8个赞

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


查看完整回答
反对 回复 2021-06-29
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信