python - python装饰器中的foo=bar(foo)和something=bar(foo)有什么区别?

标签 python python-2.7 decorator python-decorators

我读到我们可以在 python 中创建任何函数的引用,但我也读到在创建装饰器时我们使用一种称为“@”的特殊语法:例如:@decorator_function 并且这个 @decorator_function 等于 new_function=decorator_function(new_function)

所以我的怀疑是在我看来:

  1. anything = decorator_function(new_function)
  2. new_function=decorator_function(new_function)

两者都在扮演闭包的角色,但结果不同。那么两者之间的最大区别是什么?

示例代码:

def deco(fn):
    def wrapper(*args):
        print('called')
        return fn(*args)

    return wrapper


def something(x):
    if x == 0:
        print('first')
        something(x+1)
    else:
        print('hello')


print('new name')
a = deco(something)
a(0)
print('\nreassigning to the same name')
something = deco(something)
something(0)

最佳答案

您编写的原始 something 函数递归调用 something,而不是 a

如果把deco(something)赋值给a,那么something还是原来的函数,递归调用会调用原来的功能:

  • 新函数调用原函数
  • 原始函数查找东西,找到原始函数
  • 原始函数调用原始函数...

如果您将 deco(something) 分配给 something,那么 something 现在就是新函数,递归调用将调用新函数功能:

  • 新函数调用原函数
  • 原始函数查找东西,找到新函数
  • 原函数调用新函数
  • 新函数调用原函数...

关于python - python装饰器中的foo=bar(foo)和something=bar(foo)有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899385/

相关文章:

c# - 从基类创建继承类

使用 {} 样式的 python 日志记录毫秒格式

python - 进行条件 django 查询的更好方法

python /Tkinter : Getting the full Event name?

python - 从表单中检索数据?

excel - AttributeError,使用 Pandas 从ipython写回Excel

python - Python 的 property() 应该用作装饰器还是保存到变量中?

python - Django 休息问题 : get_extra_actions with listApiView

python - 加密。如何用python3存储盐?

C函数修饰/多态