Python中带参数的装饰器

装饰器本身是用来是为一个函数是实现新的功能,并且不改变原函数的代码以及调用方式。

遇到这样一种问题:

众多函数调用了你写的装饰器,但客户有需求说,我想实现我可以随之控制装饰器是否生效。

那你就不可能在得到命令的时候去原函数头部去做删除和添加装饰器调用的命令。这是就可以用到带参数的装饰器,定义一个开关,调用装饰器的时候,把这个装饰器的开关参数给传递进去,这样当开关打开的时候装饰器生效,关闭的时候则只执行原函数的代码。

 

举例:开关参数为True的时候执行过程:

 1 F = True          #step 1 装饰器的开关变量
 2 def outer(flag):  #step 2
 3     def wrapper(func): #step 4
 4         def inner(*args,**kwargs): #stpe 6
 5             if flag:               #step 9
 6                 print('before')   #step 10
 7                 ret = func(*args,**kwargs)  #step 11  执行原函数
 8                 print('after')             #step13
 9             else:
10                 ret = func(*args,**kwargs)
11                 print('123')
12             return ret                     #step 14
13         return inner    #step 7
14     return wrapper     #step 5
15 
16 @outer(F)   #先执行step 3 :outer(True)这个函数,然后step 6:@wrapper   #此处把开关参数传递给装饰器函数
17 def hahaha():
18     pass    #step 12
19 hahaha()    # step 8    相当于inner()

开关参数为False的时候执行过程:

 1   F = False          #stpe1 装饰器的开关变量
 2   def outer(flag):  #step 2
 3       def wrapper(func): #step 4
 4           def inner(*args,**kwargs): #stpe 6
 5               if flag:               #step 9
 6                   print('before')   
 7                   ret = func(*args,**kwargs)    
 8                   print('after')             
 9               else:
10                  ret = func(*args,**kwargs)    #step 10  执行原函数
11                  print('123')                 #step 12
12              return ret                     #step 13
13          return inner    #step 7
14      return wrapper     #step 5

 

转载于:https://www.cnblogs.com/eric_yi/p/7255455.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值