python-装饰器案例1

旧巷老猫 提交于 2019-12-08 03:27:27

python-装饰器案例1

高阶函数+嵌套函数=装饰器

例1:

import time
def timer(func):
    def deco():
        start_time=time.time()
        func()
        stop_time=time.time()
        print("kezi the %s"%(stop_time-start_time))
    return deco
@timer
def test1():
    time.sleep(3)
    print ("in the test1")
@timer
def test2():
    time.sleep(3)
    print("in the test2")

#test1=timer(test1)=@timer
test1()

#test2=timer(test2)=@timer
test2()


打印结果
in the test1
kezi the 3.0000288486480713
in the test2
kezi the 3.0009706020355225

 

例2  代参数的装饰

import time
def timer(func):
    def deco(*arg1,**age2):
        start_time=time.time()
        func(*arg1,**age2)
        stop_time=time.time()
        print("kezi the %s"%(stop_time-start_time))
    return deco
@timer
def test1():
    time.sleep(3)
    print ("in the test1")
@timer
def test2():
    time.sleep(3)
    print("in the test2")
@timer
def test3(name,age):
    time.sleep(3)
    print("in the test3:",name,age)

# #test1=timer(test1)=@timer
test1()
#
# #test2=timer(test2)=@timer
test2()
test3("kezi",33)

打印结果
in the test1
kezi the 3.00183367729187
in the test2
kezi the 3.0006985664367676
in the test3: kezi 33
kezi the 3.000452756881714

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!