这两个看似做同样事情的装饰器有什么区别呢?

What is the difference between these two decorators that are seemingly doing the same?

所以这是一个通用的装饰器:

示例 #1:

def decorator(or_func):

    def wrapper(*args, **kwargs):
        print(f'ran before {or_func.__name__} function')
        return or_func(*args, **kwargs)
    
    return wrapper

@decorator
def displayy(id, id2):
    print(f'display is running with the id {id} and {id2}')

displayy(8, 17)

因此,作为一名自学成才的开发人员,我尝试想出新的做事方式(通常是愚蠢的想法),然后进行某种利弊分析。所以我想到了这个:

示例 #2:

def decorator(or_func):
    print(f'ran before {or_func.__name__} function')
    return or_func

@decorator
def displayy(id, id2):
    print(f'display is running with the id {id} and {id2}')

displayy(8, 17)

在我的脑海里,当我写这篇文章时,我预计会出现错误,因为我实际上没有将所需的参数传递给 or_func。但实际上效果是一样的!

你看,当我提出示例 2 时,我认为优点是“它更短”,但在 return 中“它不能接受任何参数”我认为这是因为第一层函数装饰器将原始函数作为参数。所以这就是为什么我们 return 在示例 1 中使用包装函数来接收参数。但是现在我很困惑。

所以我的问题是

  1. 为什么改用示例 #1 更好?
  2. 示例 #1 可以做而示例 #2 不能做的事情是什么?
  3. 尽管我没有通过 (*args, **kwargs)displayy 函数如何接受正确的参数?

他们做的不一样。在第二个示例中,print(f'ran before {or_func.__name__} function') 仅在您装饰函数时被调用,而不是在您 运行 之后的“装饰”函数时被调用。你实际上并没有改变功能,它与

相同
print(f'ran before {or_func.__name__} function')

def displayy(id, id2):

    print(f'display is running with the id {id} and {id2}')

在第二个例子中尝试 运行ning display 第二次看看我的意思。