定义:装饰器本质是函数(装饰其他函数)就是为其他函数添加附加功能
原则:
1、不能修改被装饰的函数的源代码
2、不能修改被装饰的函数的调用方式
实现装饰器的知识储备:
1、函数既变量
def foo():
print("in the foo")
bar()
def bar():
print("in the bar")
foo()
输出:
in the foo
in the bar
2、高阶函数
a:把一个函数名当做实参传给另一个函数。(不修改被装饰的函数代码,为其增加新的功能)
import
timedef bar():
time.sleep(1)
print("in the bar")
def test1(func):
start_time = time.time()
func()
end_time = time.time()
print("use time is %s" % (end_time - start_time))
test1(bar)
输出:
in the bar
use time is 1.0030739307403564
b:返回值中包含函数名。(不修改函数的调用方式)
import time
def bar():
time.sleep(3)
print("in the bar")
def test(func):
print(func)
return funca = test(bar)
a()
输出:
<function bar at 0x108347048>
in the bar
3、嵌套函数
def foo():
print("in the foo")
def bar():
print("in the bar")
bar()
foo()
输出:
in the foo
in the bar
通过高阶函数+嵌套函数 实现 装饰器
import time
def timer(func):
def bar(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print("the func run time is %s" % (end_time-start_time))
return bar
@timer
def test1():
time.sleep(1)
print("in the test1")
@timer
def test2(name):
time.sleep(2)
print("in the test2 %s" % name)
test1()
test2("alex")
输出:
in the test1
the func run time is 1.0011811256408691
in the test2 alex
the func run time is 2.0028319358825684