Python AOP正确实现方法介绍


如何正确有效率的实现Python AOP来为我们的程序开发起到一些帮助呢?首先我们要使用metaclass来对这一技术应用进行实现。那么具体的操作步骤将会在这里为大家呈上,希望可以给大家带来些帮助。

其实Python这类非常动态的语言要实现AOP是很容易的,所以首先我们要来先定义一个metaclass

然后我们要在__new__)这个metaclass 的时候动态植入方法到要调用地方法的前后。

具体Python AOP的实现代码如下:

  1. __author__="alex" 
  2. __date__ ="$2008-12-5 23:54:11$" 
  3. __name__="pyAOP" 
  4. '''  
  5. 这个metaclass是实现AOP的基础  
  6. '''  
  7. class pyAOP(type):  
  8. '''  
  9. 这个空方法是用来将后面的beforeop和afterop初始化成函数引用  
  10. '''  
  11. def nop(self):  
  12. pass  
  13. '''  
  14. 下面这两个变量是类变量,也就是存放我们要植入的两个函数的地址的变量  
  15. '''  
  16. beforeop=nop 
  17. afterop=nop 
  18. '''  
  19. 设置前后两个植入函数的类函数  
  20. '''  
  21. @classmethod  
  22. def setbefore(self,func):  
  23. pyAOP.beforeop=func 
  24. @classmethod  
  25. def setafter(self,func):  
  26. pyAOP.afterop=func 
  27. '''  
  28. 初始化metaclass的函数,这个函数最重要的就是第四个参数,
    dict通过这个参数我们可以修改类的属性方法)  
  29. '''  
  30. def __new__(mcl,name,bases,dict):  
  31. from types import FunctionType #加载类型模块的FunctionType  
  32. obj=object() #定义一个空对象的变量  
  33. '''  
  34. 这个就是要植入的方法,func参数就是我们要调用的函数  
  35. '''  
  36. def AOP(func):  
  37. '''  
  38. 我们用这个函数来代替将要调用的函数  
  39. '''  
  40. def wrapper(*args, **kwds):  
  41. pyAOP.beforeop(obj) #调用前置函数  
  42. value = func(*args, **kwds) #调用本来要调用的函数  
  43. pyAOP.afterop(obj) #调用后置函数  
  44. return value #返回  
  45. return wrapper  
  46. #在类的成员列表中查找即将调用的函数  
  47. for attr, value in dict.iteritems():  
  48. if isinstance(value, FunctionType):  
  49. dict[attr] = AOP(value) #找到后用AOP这个函数替换之  
  50. obj=super(pyAOP, mcl).__new__(mcl, name, bases, dict)
     #调用父类的__new__()创建self  
  51. return obj 

使用的时候,如果我们要拦截一个类A的方法调用,就这样子:

  1. class A(object):  
  2. __metaclass__ = pyaop 
  3. def foo(self):  
  4. total = 0 
  5. for i in range(100000):  
  6. totaltotal = total+1  
  7. print total  
  8. def foo2(self):  
  9. from time import sleep  
  10. total = 0 
  11. for i in range(100000):  
  12. totaltotal = total+1  
  13. sleep(0.0001)  
  14. print total 

最后我们只需要:

  1. def beforep(self):  
  2. print('before')  
  3. def afterp(self):  
  4. print('after')  
  5. if __name__ == "__main__":  
  6. pyAOP.setbefore(beforep)  
  7. pyAOP.setafter(afterp)  
  8. a=A()  
  9. a.foo()  
  10. a.foo2() 

这样子在执行代码的时候就得到了如下结果

  1. before  
  2. 100000  
  3. after  
  4. before  
  5. 100000  
  6. after 

以上就是我们对Python AOP的相关内容的介绍。

相关内容

    暂无相关文章

评论关闭