python中装饰器

在介绍装饰器之前,要先了解装饰器的相关基础知识。python中装饰器
python中装饰器
python中装饰器

嵌套函数:

python中装饰器

python中装饰器

最后引入一个基本的装饰器的例子:

__author__ = "YanFeixu"
import time
def timer(func): #timer(test1)  func=test1
    def deco(*args,**kwargs):   # 嵌套函数
        start_time=time.time()
        func(*args,**kwargs)   #run test1()
        stop_time = time.time()
        print("the func run time  is %s" %(stop_time-start_time))
    return deco   # 高阶函数
@timer  #test1=timer(test1)
def test1():
    time.sleep(1)
    print('in the test1')

@timer # test2 = timer(test2)  = deco  test2(name) =deco(name)
def test2(name,age):
    print("test2:",name,age)

test1()
test2("YanYeixu",22)

python中装饰器