码迷,mamicode.com
首页 > 其他好文 > 详细

6.5、装饰器的类型

时间:2018-02-04 00:29:46      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:重复   nbsp   color   tor   round   ora   需求   end   one   


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

【比如说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()

6.5、装饰器的类型

标签:重复   nbsp   color   tor   round   ora   需求   end   one   

原文地址:https://www.cnblogs.com/progor/p/8410952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!