了解 Python 中的装饰器。例子:
def count(f):
total=0
def decorated(*args, **kwargs):
nonlocal total
total+=1
return f(*args, **kwargs), total
return decorated
@count
def hello(name):
return f"Привет, {name}!"
print(hello("Пользователь_1"))
print(hello("Пользователь_2"))
输出:
('Привет, Пользователь_1!', 1)
('Привет, Пользователь_2!', 2)
为什么要保存变量的值total?如果再次运行整个代码,则倒计时total再次开始0。
请随意向您不太理解的代码添加调试打印:
结论:
好吧,一切似乎都清楚了:
count当解释器遇到装饰器时调用该函数@counttotal = 0count返回一个函数引用decoratedhello现在调用该函数decoratedtotal在这种情况下,函数内的变量decorated就像一个变量,该变量用于count.total每次调用hello更新了答案。
本质上,我们需要在这里谈谈闭包。对函数中初始化的
decorated变量的引用被传递给.同时,如果你用相同的装饰器装饰另一个函数,该函数将被再次调用并初始化一个新变量。第二个修饰函数将维护另一个计数器。这就是为什么装饰器的概念如此方便并且事实证明。totalcountcounttotal结论: