参考:
https://www.youtube.com/watch?v=5VCywjS8YEA
https://foofish.net/python-decorator.html
装饰器
Python 中的函数可以像普通变量一样当做参数传递给另外一个函数
我们使用装饰器的目的是为了给函数穿条裤子一样
装饰器
def bar(func):
def inner():
print('In bar:Before')
func()
print('In bar:End')
return inner
def baz(func):
def inner():
print('In baz:Before')
func()
print('In baz:End')
return inner
@bar
@baz
def foo():
print('Foo!')
foo()
应用一、计时器
# 用处计时器
import time
def timeit(func):
def inner(*args):
s=time.time()
func(*args)
e=time.time()
# f-string 格式化字符串常量
# 在Python3.6以后建议使用f-string替代format
# f'{} {}' {}内值被替代为运行时运算求值的表达式
print(f'{func.__name__} finished in {e-s} secs.')
return inner
@timeit
def slow_method(a,b):
time.sleep(2)
print(f'{a}+{b}={a+b}')
print('Done!')
slow_method(1,2)