标签:tar col nbsp out imp 通过 color *args font
闭包函数的传值方式:
方式1:通过参数传值
def func(x):
    print(x)
func(1)
方式2:闭包函数传值
def outter(x):
    def inner():
        print(x)
    return inner
f=outter(1)
f()
装饰器:
装饰指的是为被装饰器对象添加额外的功能
装饰器的实现必须遵循量大原则:
1.不修改被装饰对象的源代码
2.不修改被装饰对象的调试方式
无参装饰器的演变:
方式1:
import time
def index():
    time.sleep(3)
    print(‘Welcome to index page‘)
def outter(func):             #func=最初始的index
    # func=index
    def wrapper():
        start_time=time.time()
        func()                 #调用最原始的index
        stop_time=time.time()
        print(stop_time-start_time)
    return wrapper
index=outter(index)            #新的index=wrapper
index()                     #wrapper
方式2:当函数有形参时,思考
import time
# def index():
#     time.sleep(1)
#     print(‘Welcome to index page‘)
#     return 123
def home(name):
    time.sleep(2)
    print(‘Welcome %s to home page‘%name)
#==============装饰器
def outter(func): #func=最初始的index
    # func=index
    def wrapper(name):
        start_time=time.time()
        res=func(name)        #调用最原始的index 同样也调用最原始的home,但是home在传值的时候是有形参name在里面的
        stop_time=time.time()
        print(stop_time-start_time)
        return  res
    return wrapper
# index=outter(index)    #新的index=wrapper
# index()
home=outter(home)    #新的home=wrapper
home(‘yangzhizong‘)
方式3:
import time
def index():
    time.sleep(1)
    print(‘Welcome to index page‘)
def home(name):
    time.sleep(2)
    print(‘Welcome %s to home page‘%name)
#==============装饰器
def timmer(func): #func=最初始的index和最初始的home
    # func=index
    def wrapper(*args,**kwargs):
        start_time=time.time()
        res=func(*args,**kwargs)        #调用最原始的index 同样也调用最原始的home,但是home在传值的时候是有形参name在里面的
        stop_time=time.time()
        print(stop_time-start_time)
        return  res
    return wrapper
index=timmer(index)    #新的index=wrapper
index()
home=timmer(home)    #新的home=wrapper
home(‘yangzhizong‘)
方式4:最终版
import time
def timmer(func):
    def wrapper(*args,**kwargs):
        start_time=time.time()
        res=func(*args,**kwargs)
        stop_time=time.time()
        print(stop_time-start_time)
        return  res
    return wrapper
@timmer                             #index=timmer(index)
def index():
    time.sleep(1)
    print(‘Welcome to index page‘)
@timmer                             #home=timmer(home)
def home(name):
    time.sleep(2)
    print(‘Welcome %s to home page‘%name)
index()
home(‘yangzhizong‘)
装饰器:(固定不变的书写格式)
def outer(func):
    def inner(*args,**kwargs):
        res=fun(*args,**kwargs)
        return res
    res inner
标签:tar col nbsp out imp 通过 color *args font
原文地址:https://www.cnblogs.com/yangzhizong/p/9168858.html