装饰器

装饰器

开放封闭原则:

扩展是开放的(增加新功能)

修改源码是封闭(修改已经实现的功能)

在不改变源码及调用方式的基础上额外增加新的功能

装饰器

用来装饰的工具

版一

import time
start_time = time.time()
def func():
    time.sleep(2)  #睡眠   模拟网络延迟
    print("我要飞")
func()
print(time.time() - start_time)
start_time = time.time()
def foo():
    time.sleep(3)
    print("我是小明,我飞的比你高")
foo()
print(time.time() - start_time)
#
我是小明,我飞的比你高
3.0025882720947266

版二

def times(f):
    start_time = time.time()
    f()
    print(time.time() - start_time)
def foo():
    time.sleep(3)
    print("我是小明,我飞的比你高")
def func():
    time.sleep(1)
    print("我是叶儿,我起不来")
s = func
func = times

s = foo
foo = times
foo(s)

###                    当你不懂程序的时候  debug 是个好东西
我是小明,我飞的比你高
3.0032668113708496

版三

ef times(f):
    def inner():
        start_time = time.time()
        f()
        print(time.time() - start_time)
    return inner

def foo():
    time.sleep(1)
    print("我是立业")       

foo = times(foo)
foo()

###
我是立业
1.0018110275268555

low版

def wrapper(f):
    def inner(*args,**kwargs):
        start_time = time.time()
        f(*args,**kwargs)
        print(time.time() - start_time)
    return inner

def func(*args,**kwargs):
    print(f"这是{args}函数,李烨还是不行")
    time.sleep(2)

func = wrapper(func)
func("alex","sur")

高级

def wrapper(f):
    def inner(*args,**kwargs):
        start_time = time.time()
        f(*args,**kwargs)
        print(time.time() - start_time)
    return inner
@wrapper # func = wrapper(func)
def func(*args,**kwargs):
    print(f"这是{args}函数,李烨还是不行")
    time.sleep(2)
    @wrapper  # func = wrapper(foo)
def foo(*args,**kwargs):
    print(f"这是{args}函数,常鑫穿裙子")
    time.sleep(3)
func = wrapper(func)
foo = wrapper(foo)
func("alex","sur")
foo("alex","sur")


####

这是('alex', 'sur')函数,李烨还是不行
2.0036680698394775
2.0037569999694824
这是('alex', 'sur')函数,常鑫穿裙子
3.0051209926605225
3.005230188369751



语法糖 ——— 甜

语法糖必须放在被装饰的函数正上方

func = wrapper(func)

func = wrapper(foo)

def wrapper(f):
    def inner(*args,**kwargs):
        start_time = time.time()
        ret = f(*args,**kwargs)
        print(time.time() - start_time)
        return ret
    return inner
@wrapper
def func(*args,**kwargs):
    print(f"这是{args}函数,李烨还是不行")
    time.sleep(2)
    return"alex"
print(func())

这是()函数,李烨还是不行
2.00323486328125
alex

posted @ 2019-07-23 16:06  挂机兄  阅读(140)  评论(0编辑  收藏  举报