“at”(@)符号在Python中有什么作用?
2022-09-05 01:19:43
符号在Python中有什么作用?@
行首的符号用于类和函数装饰器:@
最常见的Python装饰器是:
一条线中间的可能是矩阵乘法:@
class Pizza(object):
def __init__(self):
self.toppings = []
def __call__(self, topping):
# When using '@instance_of_pizza' before a function definition
# the function gets passed onto 'topping'.
self.toppings.append(topping())
def __repr__(self):
return str(self.toppings)
pizza = Pizza()
@pizza
def cheese():
return 'cheese'
@pizza
def sauce():
return 'sauce'
print pizza
# ['cheese', 'sauce']
这表明您在装饰器之后定义的 // 基本上只是作为符号之后的 / 传递给 / 。function
method
class
argument
function
method
@
微框架 Flask 从一开始就以以下格式引入了装饰器:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
这反过来又转化为:
rule = "/"
view_func = hello
# They go as arguments here in 'flask/app.py'
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
pass
意识到这一点终于让我对Flask感到平静。