设为首页 加入收藏

TOP

Python装饰器基础知识
2018-08-31 18:27:15 】 浏览:134
Tags:Python 装饰 基础知识

装饰器:本质是函数(装饰其他函数)就是为其他函数添加附加功能


原则:


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’)



import time


def timer(func):  #timer(test1)  func=test1


    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)  #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():
    time.sleep(3)
    print('in the test1')


@timer
def test2(name,age):
    time.sleep(3)
    print('in the test2',name,age)


#test1 = timer(test1)
print(test1)
test1()  #--->deco
test2('martin',18) 



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用C++对物理网卡/虚拟网卡进行.. 下一篇Java Object类的equals()方法

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目