python之装饰器学习

#在讲装饰器之前先说说嵌套函数
#定义:在函数体内重新声明另一个函数
x=0
def test():
    x=1
    print("in the test")
    def test_1():
       x=2
       print("in the test_1")
       def  test_2():
           x=3
           print('in the test_2')
           print(3)
       test_2()
    test_1()
test()
#输出结果:
# in the test
# in the test_1
# in the test_2
# 3
#装饰器  本质上就是函数  作用就是为函数添加其他功能
#原则:装饰器不能修改被装饰函数的源代码以及不能修改被装饰函数的调用方式
import time
def test():
    time.sleep(3)
    print("in the test")
#现在我要在test函数添加一个新功能,就是统计运行test函数花费了多少时间
def timer(func):
    start_time=time.time()
    func()
    stop_time=time.time()
    print("总共消费时间;{}".format(stop_time-start_time))
timer(test)
#运行结果:
# in the test
# 总共消费时间;3.0066416263580322
#这样做虽然实现了这个功能,没有修改test的源代码,但是修改了函数的调用方式,所以下面来改进通过添加嵌套函数
#现在通过嵌套函数来实现
import time
def test():
    time.sleep(3)
    print("in the test")

def timer(func):
    def docarote():
        start_time=time.time()
        func()
        stop_time=time.time()
        print("总共消费时间;{}".format(stop_time-start_time))
    return docarote 
test=timer(test)
test()
#运行结果
# in the test
# 总共消费时间;3.0049240589141846

 上面这一步虽然实现了为test()函数添加新功能,也没有改变他的调用方式,但却多了test=timer(test),所以在看最终装饰器

#现在通过嵌套函数来实现
import time
def timer(func):
    def docarote():
        start_time=time.time()
        func()
        stop_time=time.time()
        print("总共消费时间;{}".format(stop_time-start_time))
    return docarote
@timer  #这一步就相当于 test=timer(test)
def test():
    time.sleep(3)
    print("in the test")
test()
#运行结果
# in the test
# 总共消费时间;3.0049240589141846

猜你喜欢

转载自www.cnblogs.com/Be-your-own-hero/p/11298753.html