zoukankan      html  css  js  c++  java
  • 6.5、装饰器的类型


    当需求相似的函数需要使用装饰器时,这种差别不大的函数,如果定义多个相似的装饰器来各自装饰特定函数就太过赘余了。

    【比如说A需要记录日志功能的装饰器,B需要记录日志+发送给指定管理员功能的装饰器,它们之间有重合的功能--记录日志】【如果相同代码量很大,那么新弄的代码重复量就更大了】

    为了解决这种问题,我们可以使用装饰器的类型来解决,与之前的区别只是再加上一层嵌套而已:

    def decorator(my_type):
        def outwrapper(func):
            def wrapper(*args,**kwargs):
                print("logged done")#假功能
                if my_type=='A':
                    res = func()
                    return res
                else :
                    print("send done")#假功能
                    res = func()
                    return res
            return wrapper
        return outwrapper
    
    @decorator('A')
    def testA():
        print("run in A")
        return
    
    @decorator('B')
    def testB():
        print("run in B")
        return
    
    testA()
    print("-------------")
    testB()

    相当于,当装饰器给定参数时,【装饰器原本默认有一个函数对象参数】,相当于会选择第二次再传入默认的函数对象参数

    原本是:

    test3=outwrapper(func)     =>     test3=wrapper()
    现在是:
    test3=decorator(A) => outwrapper(func) => test3=wrapper()
  • 相关阅读:
    选择排序
    冒泡排序
    排序算法
    排序的稳定性
    散列表查找的代码实现
    处理散列冲突的方法
    jQuery 实时监听input
    PhpStorm
    Memcache 学习
    豆瓣第三方登录
  • 原文地址:https://www.cnblogs.com/progor/p/8410952.html
Copyright © 2011-2022 走看看