python装饰器使用

# Author:Sooele
                    #装饰器
#后面嵌套函数。
import time
def timer(func): #time(test1)   func=test1
    def deco():
        start_time = time.time()
        func() #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(3)
    print('in the test1')
@timer #等于test2=timer(test2)
def test2():
    time.sleep(3)
    print('in the test2')
test1()
test2()
# test1=timer(test1) #这里执行的是的返回值是deco!!##deco的值是test1嵌套
# test1() #执行的是deco
# #装饰器:
# #定义: 本质是函数,(装饰其他函数)。就是为了其他函数添加附加功能!
# #原则:1.不能修改被装饰的函数源代码
#         2不能修改被装饰的函数调用方式
# 实现装饰器知识储备:
# 1函数即"变量"
# 2高阶函数
    # a:把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码情况下为其添加功能)
    # b:返回值中包含函数名(不修改函数的调用方式)
# 3嵌套函数
# 高阶函数+嵌套函数=》装饰器
###
 #####有参数插入的装饰器使用
import time
def timer(func): #time(test1)   func=test1
    def deco(*args,**kwargs):  #缺少(arg1)参数无法进行
        start_time = time.time()
        func(*args,**kwargs) #run test2()
        stop_time = time.time()
        print("the func run time is %s" %(stop_time-start_time))
    return  deco
@timer #等于test2=timer(test2)   == deco      test2(name)==deco(name)
def test2(name,age):
    print("test2",name,age)
test2("Sooele",22)