ASP站长网装饰器:本质是函数(装饰其他函数)就是为其他函数添加附加功能
 
原则:
 
1、不能修改被装饰的函数的源代码
 
2、不能修改被装饰的函数的调用方式
 
装饰器对其被装饰的函数是完全透明的
 
基础知识
 
1、函数即“变量”   定义一个函数相当于就是把函数体赋值给函数名
 
def test():
 
    pass
 
test -->>'函数体'
 
2、高阶函数
 
1、把一个函数名当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能) 2、返回值中包含函数名(不修改函数的调用方式)
 
import  time
def  bar():
    time.sleep(3)
    print('in the bar')
 
def test1(func):
    start_time = time.time()
    func()  #run bar
    stop_time = time.time()
    print('the fun run time is %s' %(stop_time-start_time))
 
 
test1(bar)
bar()
 
 
 
import  time
def bar():
    time.sleep(3)
    print('in the bar')
 
 
def test2(func):
    print(func)
    return func
 
test2(bar)
 
bar = test2(bar)
bar()
 
 
 
 
 
3、嵌套函数
 
foo():
    ()
    bar():
        ()
    bar()
 
foo()
 
 
 
高阶函数+嵌套函数 =》装饰器
 
1、不带参数的装饰器
 
import time
 
def timer(func):  #timer(test1)  func=test1
 
    def deco():
        start_time = time.time()
        func()  #run test1
        stop_time = time.time()
        print('the fun run time is %s' %(stop_time-start_time))
    return deco
 
@timer  #test1 = timer(test1)  等同于这个,得到的是deco函数的返回值
def test1():
    time.sleep(3)
    print('in the test1')
 
 
test1()  #--->deco
 
 
 
代码执行过程
 
1、导入模块
 
2、def timer(func)
 
3、@timer   自动执行将test1传递给timer函数执行,之后返回deco函数的返回值
 
4、当执行到test1()函数时候,跳转到deco函数去执行
 
2、带参数的装饰器
 
import time
 
def timer(func):  #timer(test1)  func=test1
 
    def deco(arg1):
        start_time = time.time()
        func(arg1)  #run test1
        stop_time = time.time()
        print('the fun run time is %s' %(stop_time-start_time))
    return deco
 
@timer  #test1 = timer(test1)  等同于这个
def test1(name):
    time.sleep(3)
    print('in the test1',name)
 
 
test1('martin')  #--->deco(‘martin’)

dawei

【声明】:九江站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。