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

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

1、装饰器的理论:

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

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

2、装饰器的简单理解

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

  注意点:

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

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

3、装饰器的组成方式:

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

  有关高阶函数的理解:

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

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

  嵌套函数的理解:

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

  语法糖:

      写法:@xx  ,一般写在函数的上方

 

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:

复制代码

 

posted @   Syw_文  阅读(1236)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2017-06-20 软件需求关注点!
2017-06-20 测试用例中遇到的常见问题!
点击右上角即可分享
微信分享提示