python修饰器

2019-11-08  本文已影响0人  Hammon

1 什么是装饰器

2装饰器由什么组成

def f1():
    def f2():
        def f3():
            print('from f3')
        f3()
    f2()

f1()

基本实现装饰器
import time

"""
定义一个函test,在不改函数源代码,和调用方法情况下得到其运行时间
def test():
    time.sleep(2)
    print("函数test运行了")
    print("函数test运行结束了")
"""


# 函数名作为入参--->高阶函数
def timer(func):
    def wrapper():
        # 函数执行前的时间
        start_time = time.time()
        func()
        # 函数执行后的时间
        end_time = time.time()
        # 相减得出运行时间
        res = end_time - start_time
        print('运行时间是:%s' %(res))
        return res

    return wrapper


def test():
    time.sleep(2)
    print("函数test运行了")
    print("函数test运行结束了")

"""1.把函数名test作为入参传入调用timer,
2.timer运行后得到一个返回值timer函数嵌套的wrapper函数的内存地址
3.把这个内存地址存到test变量内
4.test+(),运行这个返回的内存地址即wrapper函数,
wrapper函数内拿到真正的原始的test函数名,
并且加了计时并运行test函数,得到运行时间res
"""
test = timer(test)
test()
用@语法堂实现装饰器
import time

"""
定义一个函test,在不改函数源代码,和调用方法情况下得到其运行时间
def test():
    time.sleep(2)
    print("函数test运行了")
    print("函数test运行结束了")
"""


# 函数名作为入参--->高阶函数
def timer(func):
    def wrapper():
        # 函数执行前的时间
        start_time = time.time()
        func()
        # 函数执行后的时间
        end_time = time.time()
        # 相减得出运行时间
        res = end_time - start_time
        print('运行时间是:%s' %(res))
        return res

    return wrapper


@timer#------>=之前包装的 test = timer(test)
def test():
    time.sleep(2)
    print("函数test运行了")
    print("函数test运行结束了")

# test = timer(test)
test()
上一篇 下一篇

猜你喜欢

热点阅读