前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现自己的AOP

Python实现自己的AOP

作者头像
py3study
发布2020-01-10 11:21:52
1K0
发布2020-01-10 11:21:52
举报
文章被收录于专栏:python3

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档