Python AOP正確實現方法介紹
作者:佚名
Python AOP的實現方法其實比較簡單,我們在這里將會通過一段代碼的解讀來為大家詳細分析一下這一操作的每一步驟,方便大家學習。
如何正確有效率的實現Python AOP來為我們的程序開發起到一些幫助呢?首先我們要使用metaclass來對這一技術應用進行實現。那么具體的操作步驟將會在這里為大家呈上,希望可以給大家帶來些幫助。
其實Python這類非常動態的語言要實現AOP是很容易的,所以首先我們要來先定義一個metaclass
然后我們要在__new__()這個metaclass 的時候動態植入方法到要調用地方法的前后。
具體Python AOP的實現代碼如下:
- __author__="alex"
- __date__ ="$2008-12-5 23:54:11$"
- __name__="pyAOP"
- '''
- 這個metaclass是實現AOP的基礎
- '''
- class pyAOP(type):
- '''
- 這個空方法是用來將后面的beforeop和afterop初始化成函數引用
- '''
- def nop(self):
- pass
- '''
- 下面這兩個變量是類變量,也就是存放我們要植入的兩個函數的地址的變量
- '''
- beforeop=nop
- afterop=nop
- '''
- 設置前后兩個植入函數的類函數
- '''
- @classmethod
- def setbefore(self,func):
- pyAOP.beforeop=func
- @classmethod
- def setafter(self,func):
- pyAOP.afterop=func
- '''
- 初始化metaclass的函數,這個函數最重要的就是第四個參數,
dict通過這個參數我們可以修改類的屬性(方法)- '''
- def __new__(mcl,name,bases,dict):
- from types import FunctionType #加載類型模塊的FunctionType
- obj=object() #定義一個空對象的變量
- '''
- 這個就是要植入的方法,func參數就是我們要調用的函數
- '''
- def AOP(func):
- '''
- 我們用這個函數來代替將要調用的函數
- '''
- def wrapper(*args, **kwds):
- pyAOP.beforeop(obj) #調用前置函數
- value = func(*args, **kwds) #調用本來要調用的函數
- pyAOP.afterop(obj) #調用后置函數
- return value #返回
- return wrapper
- #在類的成員列表中查找即將調用的函數
- for attr, value in dict.iteritems():
- if isinstance(value, FunctionType):
- dict[attr] = AOP(value) #找到后用AOP這個函數替換之
- obj=super(pyAOP, mcl).__new__(mcl, name, bases, dict)
#調用父類的__new__()創建self- return obj
使用的時候,如果我們要攔截一個類A的方法調用,就這樣子:
- class A(object):
- __metaclass__ = pyaop
- def foo(self):
- total = 0
- for i in range(100000):
- totaltotal = total+1
- print total
- def foo2(self):
- from time import sleep
- total = 0
- for i in range(100000):
- totaltotal = total+1
- sleep(0.0001)
- print total
最后我們只需要:
- def beforep(self):
- print('before')
- def afterp(self):
- print('after')
- if __name__ == "__main__":
- pyAOP.setbefore(beforep)
- pyAOP.setafter(afterp)
- a=A()
- a.foo()
- a.foo2()
這樣子在執行代碼的時候就得到了如下結果
- before
- 100000
- after
- before
- 100000
- after
以上就是我們對Python AOP的相關內容的介紹。
【編輯推薦】
責任編輯:曹凱
來源:
博客園