简体   繁体   English

python如何在其中找到修饰的函数?

[英]How can python find decorated functions within it?

In the following code how does app.run() find that hello() exists? 在以下代码中,app.run()如何发现hello()存在? I browsed the code and couldn't find the answer. 我浏览了代码,找不到答案。 I think the hello() doesn't get added to a list of routes until it is called, but how does it get called? 我认为hello()直到被调用才被添加到路由列表中,但是如何调用它呢?

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

I'm not interested in Flask in particular. 我对Flask尤其不感兴趣。 I'd just like to implement something similar myself. 我只想自己实现类似的功能。

What is this design pattern called? 这种设计模式称为什么?

Your assumption is wrong. 您的假设是错误的。 Decorators are themselves executable code, and they are called when the function they decorate is defined , ie at import time. 装饰器本身是可执行代码,并且在定义装饰的函数(即在导入时)时调用它们。 The code within the decorator can then add the route to its registry. 装饰器中的代码然后可以将路由添加到其注册表中。

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

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