Skip to main content
 首页 » 编程设计

python之装饰器如何标记一个函数

2025年05月04日14duanxz

我正在阅读具有以下代码的基本 Flask 教程:

from flask import Flask 
app = Flask(__name__) 
 
@app.route("/") 
def hello(): 
    return "Hello World!" 
 
if __name__ == "__main__": 
    app.run() 

我还从许多网站了解了 Python 装饰器的基础知识,包括 Stackoverflow Decorators

我假设在前面的代码中,函数 hello 将被更改和修饰,为了运行应用程序,我需要调用函数 hello() 某个地方。 Flask 如何确定它必须调用的函数的名称。

只是用装饰器包装函数定义是否以某种方式标记了该函数?如果是,怎么办?

例如在下面的代码中,在某处我调用了我装饰过的函数:

def decorate(foo): 
    print("I'm doing a lot of important stuff right now") 
 
    def inner(): 
        print("Some stuff 1") 
        foo() 
        print("Some stuff 2") 
 
    return inner 
 
@decorate 
def hello(): 
    print("Hello") 
 
hello() 

请您参考如下方法:

在 decorate 中,foo 是您正在装饰的函数(在本例中,hello)。您可以将该函数存储在某处的列表或字典中,因为它是一个普通对象。

例如:

decorated_functions = [] 
 
def decorate(foo): 
    def inner(): 
        print("Some stuff 1") 
        foo() 
        print("Some stuff 2") 
 
    decorated_functions.append(inner) 
    return inner 
 
@decorate 
def hello(): 
    print("Hello") 
 
## The above is the same as: 
# def hello(): 
#     print("Hello") 
# hello = decorate(hello) 
 
print(decorated_functions[0] == hello) # prints True 
decorated_functions[0]() # prints "Some stuff 1", "Hello", and "Some stuff 2" 
hello() # same as above