了解装饰器的细节

问题描述 投票:0回答:1

假设我们有以下代码:

def  div(a,b):
    print(a/b)

def  helper_function(func):
    def inner(a,b):
        if a<b:
            a,b=b,a
        return func(a,b)
    return inner
@helper_function
# div =helper_function(div)
div(2,4)

当我运行此代码时,它返回以下错误:

  div(2,4)
    ^^^
SyntaxError: invalid syntax

但是当我激活这条线时:

div =helper_function(div)

然后它返回:2.0,但是我需要使用这个语句@,第一个函数的错误部分是怎样的,它看起来像这样:Decorators 请解释一下我做错了什么?

python python-decorators
1个回答
2
投票

该问题是由于

@helper_function
装饰器放置不正确造成的。装饰器应放置在它们要修改的函数定义的正上方:

def helper_function(func):
    def inner(a, b):
        if a < b:
            a, b = b, a
        return func(a, b)
    return inner

@helper_function
def div(a, b):
    print(a / b)

div(2, 4)
© www.soinside.com 2019 - 2024. All rights reserved.