Python实现自己的AOP

Java中的AOP可以用JDK的动态代理和cglib来实现,将需要拦截的方法前后可以额外添加些功能。

Python中有许多方法去实现AOP,现在先介绍第一种比较简单的:

1)利用with...as...

Python的with...as...子句是用于控制执行流程的语句,结构是with expression as variable,这里的expression里定义拦截的方法前后需要执行的逻辑,分别定义“__enter__”和“__exit__”方法,“__enter__”方法定义拦截方法执行前的逻辑,“__exit__”方法定义拦截方法执行后的逻辑,with...as...子句的主体是拦截的方法执行的逻辑,variable变量是用来接收“__enter__”方法返回的值,下面来看个示例:

class AOP: 
     def __enter__(self): 
          print("before action enter") 
          return 1 
 
     def __exit__(self, *args):
          print("after action enter")
          return 0
 
def Myfunction(): 
     print ('Myfunction() called and processed ')
     return 111 

def Myfunction1(): 
     print ('Myfunction1()  called and processed')
     return 222


def MyMain():
           with AOP() as AOPValue:
                      print ('AOPValue is %s'%AOPValue)
                      Myfunction()
                      Myfunction1()
          
if __name__ == '__main__':
           MyMain()

 
最后输出的结果是:

before action enter
AOPValue is 1
Myfunction() called and processed
Myfunction1()  called and processed
after action enter

PS:with子句中的variable接收的是__enter__方法的返回值。这是with子句的基本用法

2)利用contextlib实现AOP

Python核心库中的contextlib中的contextmanager来实现AOP就非常简单了,contextmanager是一个装饰器,具体用法如下示例:

from contextlib import contextmanager 

#define inteceptors

@contextmanager 
def AOPfunc(name): 
    print ("before:some actions done") 
    yield 
    print ("after:some actions done ") 

#normal service flow 
def BusinessProcess1(): 
     print ('BusinessProcess1()')
     return 111 

def BusinessProcess2(): 
     print ('BusinessProcess2()')
     return 111

def BusinessProcess3(): 
     print ('BusinessProcess3()')
     return 111

#main flow
def MyMain():
           with AOPfunc("aop"):
                      BusinessProcess1()
                      BusinessProcess2()
                     
           with AOPfunc("aop"):
                       BusinessProcess3()


if __name__ == '__main__':
           MyMain()

 
运行结果是:
 
before:some actions done
BusinessProcess1()
BusinessProcess2()
after:some actions done
before:some actions done
BusinessProcess3()
after:some actions done
 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值