装饰器如何标记一个函数?

Kar*_*and 2 python decorator flask python-decorators

我正在学习基本的 Flask 教程,其中包含以下代码:

from flask import Flask
app = Flask(__name__)

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

if __name__ == "__main__":
    app.run()
Run Code Online (Sandbox Code Playgroud)

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

我假设在前面的代码中,函数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()
Run Code Online (Sandbox Code Playgroud)

Col*_*Two 5

在 中decoratefoo是您要装饰的函数(在本例中为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
Run Code Online (Sandbox Code Playgroud)