简体   繁体   English

我在哪里用这个装饰器代码犯了错误?

[英]Where I am making a mistake with this decorator code?

I am trying to understand the concept of decorators in python when we have different arguments (In fact I am not sure how to pass arguments to the decorator).当我们有不同的参数时,我试图理解 python 中装饰器的概念(实际上我不确定如何将参数传递给装饰器)。 I have written the small and simple code below but I am not able to run it:我写了下面的小而简单的代码,但我无法运行它:

def advance(*arg, function):
    result = a * function(b, c)
    print(result)

@advance
def Sum1(b, c):
    return b + c

print(Sum1(1, 2, 3))

When running the code, I get TypeError: advance() missing 1 required keyword-only argument: 'function'.运行代码时,我得到TypeError: advance() missing 1 required keyword-only argument: 'function'.

Decorator has to return a new function, so you would like to have something like:装饰器必须返回一个新函数,所以你想要这样的东西:

def advance(function):
    def wrapped(a, b, c):
        return a * function(b, c)
    return wrapped

@advance
def Sum1(b, c):
    return b + c

print(Sum1(10, 2, 3))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在代码中犯了什么错误? - What mistake am I making in my code? 投放时我犯了什么错误? - What mistake am I making while casting? 我在这个python脚本中犯了什么错误? - What mistake am I making in this python script? 我在这个简历代码中做错了什么 - What's the mistake I am doing in this CV code 我收到一个错误“代码无法访问 Pylance”这是什么意思,还是我在代码中犯了任何错误? - i am getting an error "Code is unreachable Pylance" what that mean or am i doing any mistake in my code? 我犯了什么错误导致这些 Django E304 错误? - What mistake am I making to cause these Django E304 errors? 我正在编写将二进制数转换为十进制数的代码,这就是我所做的,有人可以告诉我哪里错了,(我进入 Python 1 个月 - I am making a code to turn a Binary number into decimal number, This is what I have done, Can someone tell where I am wrong, (i am 1 month into Python Django模板无法访问字典查找变量。 我在代码中犯了什么错误? - Django template unable to access a dictionary lookup variable. What mistake am I doing in code? 归并排序问题。 运行后,它永远运行。 我无法找出代码中的错误 - Problem in merge sort. After running , it runs forever. I am not able to find out the mistake in the code 运行时错误-我的代码中的错误在哪里 - Runtime error - where is the mistake in my code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM