黑猴子的家:python 装饰器实现的迭代过程

code 高阶函数 迭代装饰器一

def deco(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print("the func run time is %s" %(stop_time - start_time))

def deco1(func):
    star_time = time.time()
    return func
    stop_time = time.time()
    print("the func run time is %s" %(stop_time - start_time))

def t1():
    time.sleep(3)
    print("in the t1")

def t2():
    time.sleep(3)
    print("in the t2")

def t3():
    time.sleep(3)
    print("in the t3")

#虽然添加了功能,但是修改调用方式
deco(t1)

#第一种方式的高阶函数
t1 = deco(t1)
print(t1)

# 没有修改调用方式,但是也没有添加功能
t2 = deco1(t2)
print(t2)

打印

in the t1
the func run time is 3.0
in the t1
the func run time is 3.0
None

code -> 高阶函数 + 嵌套函数 => 装饰器方式一

def timer(funct):
    def deco():
        start_time = time.time()
        funct()
        stop_time = time.time()
        print("the func run time is %s" % (stop_time - start_time))
    return deco

t3 = timer(t3)
t3()

打印

in the t3
the func run time is 3.0

code -> 高阶函数 + 嵌套函数 => 装饰器方式二

def timer(funct):
    def deco():
        start_time = time.time()
        funct()
        stop_time = time.time()
        print("the func run time is %s" % (stop_time - start_time))
    return deco

@timer  #t4 = timer(t4)
def t4():
    time.sleep(1)
    print("in the t4")

t4()

打印

in the t4
the func run time is 1.0

code -> 高阶函数 + 嵌套函数 => 装饰器方式三

def timer(funct):
    def deco(*args,**kwargs):
        start_time = time.time()
        funct(*args,**kwargs)
        stop_time = time.time()
        print("the func run time is %s" % (stop_time - start_time))
    return deco

@timer  #t5 = timer(t5)
def t5(name):
    time.sleep(1)
    print("in the t5 %s "%name)

t5('hei hou zi')

打印

in the t5 hei hou zi 
the func run time is 1.0

你可能感兴趣的:(黑猴子的家:python 装饰器实现的迭代过程)