首页 > 编程语言 > 详细

python----装饰器(几种常见方式的使用与理解)

时间:2019-06-20 14:13:17      阅读:111      评论:0      收藏:0      [点我收藏+]

更详细的装饰器,真心实力推荐,里面介绍的很清楚,介绍可见链接:https://blog.csdn.net/buster_zr/article/details/81104551

1、装饰器的理论:

  (1)装饰器实际上就是一个函数

  (2)有2个特别之处,参数是一个函数。返回值是一个参数

2、装饰器的简单理解

  实际上就是为了给一个程序添加功能,但是该程序已经上线或者已被使用,那么就不能大批量的修改源码,这样不现实,因此就产生了装饰器。

  注意点:

    (1)不能修改被装饰的函数的源代码

    (2)不能修改被装饰的函数的调用方式

3、装饰器的组成方式:

  函数+实参高阶函数+返回值高阶函数+嵌套函数+语法糖 = 装饰器

  有关高阶函数的理解:

    (1)把一个函数名当作实参传给另外一个函数(”实参高阶函数“)

    (2)返回值中包含函数名(”返回值高阶函数“)

  嵌套函数的理解:

     嵌套函数指的是在函数内部定义一个函数,而不是调用。

4、真正装饰器的开始之处:

  装饰器在装饰时,需要在每个函数前面加上@xxx

(1) 装饰无参函数,示例代码如下:

#装饰器装饰的函数无参数
def timer(func):      #func其实指的就是test
    def deco():
        start = time.time()
        func()               #这里其实是对test的调用
        stop = time.time()
        print (stop-start)
    return deco


@timer               #test函数使用装饰器
def test():
    time.sleep(2)
    print ("test is running")
test()

打印结果:
test is running
2.003510952

 

(2)装饰有参函数,示例代码如下:

#装饰器装饰的函数有参数
def timer(func):
    def deco(*args,**kwargs):    #添加可变参数*args和**kwargs
        start = time.time()
        func(*args,**kwargs)      #这里也是一样,添加可变参数*args和**kwargs
        stop = time.time()
        print (stop-start)
    return deco


@timer
def test(value):     #test函数有个参数value,正因为装饰器timer装饰的函数test有参数value,因此在timer中的有了可变参数
    time.sleep(2)
    print ("test is running %s" %value)
test("22")

打印结果:
test is running 22
2.00424408913

 

3、带参数的装饰器,示例代码如下:

#装饰器带参数
def timer(parameter):
    def out_wapper(func):
        def wapper(*wargs,**kwargs):
            if parameter == "task1":
                start = time.time()
                func(*wargs,**kwargs)
                stop = time.time()
                print ("the task1 is run:",stop-start)
            elif parameter == "task2":
                func(*wargs, **kwargs)
                print ("the task2 is run:")
        return wapper
    return out_wapper

@timer(parameter = "task1")
def task1():
    time.sleep(2)
    print "in the task1"

@timer(parameter = "task2")
def task2():
    time.sleep(2)
    print "in the task2"

task1()
task2()

打印结果:

in the task1
(‘the task1 is run:‘, 2.002906084060669)
in the task2
the task2 is run:

 

python----装饰器(几种常见方式的使用与理解)

原文:https://www.cnblogs.com/syw20170419/p/11058203.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!