简体   繁体   English

Python函数装饰器之谜

[英]Python Function Decorator Puzzle

I recently leant the subject of python decorators, and found something strange for the below two different programs: 我最近学习了python装饰器的主题,发现以下两个不同的程序有些奇怪:

Example1: 范例1:

def deco(func):
    def inner():
        print("Running inner")
    return func

@deco
def target():
    print("Running target")

def main():
    print("Running main()")
    target()

if __name__ == "__main__":
    main()

Example2: 范例2:

def deco(func):
    print("Running inner")
    return func

@deco
def target():
    print("Running target")

def main():
    print("Running main()")
    target()

if __name__ == "__main__":
    main()

When running Example1 and Example2, it will get 2 different results: 运行Example1和Example2时,它将获得2个不同的结果:

Running main()
Running target

in Example1, and 在Example1中,以及

Running inner
Running main()
Running target

in Example2. 在Example2中。

It seems "Running inner" was lost in Example1. 似乎Example1中丢失了“ Running内部”。 Why? 为什么?

Running Example 2 will give that result because deco is executed at definition time, and in that example it prints inner immediately. 运行示例2将得到该结果,因为在定义时执行了deco ,在该示例中,它立即打印了inner

Example 1 won't print inner because you never do anything with the inner func. 示例1不会打印inner,因为您永远不会对inner func进行任何操作。 Your decorator there should be returning inner , not func ; 您的装饰师应该返回inner ,而不是func ; and inner itself should call func: inner本身应该调用func:

def deco(func):
    def inner():
        print("Running inner")
        func()
    return inner   # note change here

When you do this, you will get this result: 执行此操作时,将得到以下结果:

Running main()
Running inner
Running target

which is what you would expect from a decorator. 这是您对装饰者的期望。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM