Python AOP正確實現(xiàn)方法介紹
如何正確有效率的實現(xiàn)Python AOP來為我們的程序開發(fā)起到一些幫助呢?首先我們要使用metaclass來對這一技術(shù)應(yīng)用進行實現(xiàn)。那么具體的操作步驟將會在這里為大家呈上,希望可以給大家?guī)硇椭?/p>
其實Python這類非常動態(tài)的語言要實現(xiàn)AOP是很容易的,所以首先我們要來先定義一個metaclass
然后我們要在__new__()這個metaclass 的時候動態(tài)植入方法到要調(diào)用地方法的前后。
具體Python AOP的實現(xiàn)代碼如下:
- __author__="alex"
- __date__ ="$2008-12-5 23:54:11$"
- __name__="pyAOP"
- '''
- 這個metaclass是實現(xiàn)AOP的基礎(chǔ)
- '''
- class pyAOP(type):
- '''
- 這個空方法是用來將后面的beforeop和afterop初始化成函數(shù)引用
- '''
- def nop(self):
- pass
- '''
- 下面這兩個變量是類變量,也就是存放我們要植入的兩個函數(shù)的地址的變量
- '''
- beforeop=nop
- afterop=nop
- '''
- 設(shè)置前后兩個植入函數(shù)的類函數(shù)
- '''
- @classmethod
- def setbefore(self,func):
- pyAOP.beforeop=func
- @classmethod
- def setafter(self,func):
- pyAOP.afterop=func
- '''
- 初始化metaclass的函數(shù),這個函數(shù)最重要的就是第四個參數(shù),
dict通過這個參數(shù)我們可以修改類的屬性(方法)- '''
- def __new__(mcl,name,bases,dict):
- from types import FunctionType #加載類型模塊的FunctionType
- obj=object() #定義一個空對象的變量
- '''
- 這個就是要植入的方法,func參數(shù)就是我們要調(diào)用的函數(shù)
- '''
- def AOP(func):
- '''
- 我們用這個函數(shù)來代替將要調(diào)用的函數(shù)
- '''
- def wrapper(*args, **kwds):
- pyAOP.beforeop(obj) #調(diào)用前置函數(shù)
- value = func(*args, **kwds) #調(diào)用本來要調(diào)用的函數(shù)
- pyAOP.afterop(obj) #調(diào)用后置函數(shù)
- return value #返回
- return wrapper
- #在類的成員列表中查找即將調(diào)用的函數(shù)
- for attr, value in dict.iteritems():
- if isinstance(value, FunctionType):
- dict[attr] = AOP(value) #找到后用AOP這個函數(shù)替換之
- obj=super(pyAOP, mcl).__new__(mcl, name, bases, dict)
#調(diào)用父類的__new__()創(chuàng)建self- return obj
使用的時候,如果我們要攔截一個類A的方法調(diào)用,就這樣子:
- 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()
這樣子在執(zhí)行代碼的時候就得到了如下結(jié)果
- before
- 100000
- after
- before
- 100000
- after
以上就是我們對Python AOP的相關(guān)內(nèi)容的介紹。
【編輯推薦】