python-3.x - 运行 tmp() 的结果是什么以及为什么?

标签 python-3.x properties decorator

我认为 tmp() 与 f2() 相同。但我得到了 2 个不同的结果。

def w1(func):
    def inner():
        print("Verifying ......")
        return func()
    return inner

@w1
def f2():
   print('f2')

f2()
print("Equivalently:") 
tmp = w1(f2)
tmp()

最佳答案

tmp()f() 的答案是不同的,因为当我们赋值 tmp=w1(f2) tmp 现在指向 inner() 内部函数。请记住,当您调用 w1(f2) 时,您将 inner 作为函数返回,因为执行了此 “Verifying ......” 。当您调用 tmp() 时,它会再次使用 f2() 执行 inner()。这就是 tmp()f() 不同的原因。

关于python-3.x - 运行 tmp() 的结果是什么以及为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53567364/

相关文章:

properties - @property和@synthesize : why both?

Java Sorting : sort an array of objects by property, 对象不允许使用 Comparable

python - 是我的类内装饰器不够 Pythonic 还是 PyCharm 在 lint 警告方面不够智能?

c# - 动态创建装饰器链

python - 从 Tensorflow 模型获取预测

python - `in` 比 `__contains__` 有多少优化?

python - 如何计算两个日期/时间之间的实例数

python - 结果窗口打开,但未显示在登录页面程序的标签和文本框中

不带 IAdaptable 的 Eclipse 属性 View

Java类装饰自己