Python裝飾器 Examples:
第一步:最簡(jiǎn)單的函數(shù),準(zhǔn)備附加額外功能
# -*- coding:gbk -*-
'''示例1: 最簡(jiǎn)單的函數(shù),表示調(diào)用了兩次'''
def myfunc():
print("myfunc() called.")
myfunc()
myfunc()
第二步:使用裝飾函數(shù)在函數(shù)執(zhí)行前和執(zhí)行后分別附加額外功能
# -*- coding:gbk -*-
'''示例2: 替換函數(shù)(裝飾)
裝飾函數(shù)的參數(shù)是被裝飾的函數(shù)對(duì)象振诬,返回原函數(shù)對(duì)象
裝飾的實(shí)質(zhì)語(yǔ)句: myfunc = deco(myfunc)'''
def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func
def myfunc():
print(" myfunc() called.")
myfunc = deco(myfunc)
myfunc()
myfunc()
第三步:使用語(yǔ)法糖@來(lái)裝飾函數(shù)
# -*- coding:gbk -*-
'''示例3: 使用語(yǔ)法糖@來(lái)裝飾函數(shù)纬乍,相當(dāng)于“myfunc = deco(myfunc)”
但發(fā)現(xiàn)新函數(shù)只在第一次被調(diào)用权埠,且原函數(shù)多調(diào)用了一次'''
def deco(func):
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return func
@deco
def myfunc():
print(" myfunc() called.")
myfunc()
myfunc()
第四步:使用內(nèi)嵌包裝函數(shù)來(lái)確保每次新函數(shù)都被調(diào)用
# -*- coding:gbk -*-
'''示例4: 使用內(nèi)嵌包裝函數(shù)來(lái)確保每次新函數(shù)都被調(diào)用杈绸,
內(nèi)嵌包裝函數(shù)的形參和返回值與原函數(shù)相同形纺,裝飾函數(shù)返回內(nèi)嵌包裝函數(shù)對(duì)象'''
def deco(func):
def _deco():
print("before myfunc() called.")
func()
print(" after myfunc() called.")
# 不需要返回func,實(shí)際上應(yīng)返回原函數(shù)的返回值
return _deco
@deco
def myfunc():
print(" myfunc() called.")
return 'ok'
myfunc()
myfunc()
第五步:對(duì)帶參數(shù)的函數(shù)進(jìn)行裝飾
# -*- coding:gbk -*-
'''示例5: 對(duì)帶參數(shù)的函數(shù)進(jìn)行裝飾评也,
內(nèi)嵌包裝函數(shù)的形參和返回值與原函數(shù)相同,裝飾函數(shù)返回內(nèi)嵌包裝函數(shù)對(duì)象'''
def deco(func):
def _deco(a, b):
print("before myfunc() called.")
ret = func(a, b)
print(" after myfunc() called. result: %s" % ret)
return ret
return _deco
@deco
def myfunc(a, b):
print(" myfunc(%s,%s) called." % (a, b))
return a + b
myfunc(1, 2)
myfunc(3, 4)
第六步:對(duì)參數(shù)數(shù)量不確定的函數(shù)進(jìn)行裝飾
# -*- coding:gbk -*-
'''示例6: 對(duì)參數(shù)數(shù)量不確定的函數(shù)進(jìn)行裝飾灭返,
參數(shù)用(*args, **kwargs)盗迟,自動(dòng)適應(yīng)變參和命名參數(shù)'''
def deco(func):
def _deco(*args, **kwargs):
print("before %s called." % func.__name__)
ret = func(*args, **kwargs)
print(" after %s called. result: %s" % (func.__name__, ret))
return ret
return _deco
@deco
def myfunc(a, b):
print(" myfunc(%s,%s) called." % (a, b))
return a+b
@deco
def myfunc2(a, b, c):
print(" myfunc2(%s,%s,%s) called." % (a, b, c))
return a+b+c
myfunc(1, 2)
myfunc(3, 4)
myfunc2(1, 2, 3)
myfunc2(3, 4, 5)
第七步:讓裝飾器帶參數(shù)
# -*- coding:gbk -*-
'''示例7: 在示例4的基礎(chǔ)上,讓裝飾器帶參數(shù)熙含,
和上一示例相比在外層多了一層包裝罚缕。
裝飾函數(shù)名實(shí)際上應(yīng)更有意義些'''
def deco(arg):
def _deco(func):
def __deco():
print("before %s called [%s]." % (func.__name__, arg))
func()
print(" after %s called [%s]." % (func.__name__, arg))
return __deco
return _deco
@deco("mymodule")
def myfunc():
print(" myfunc() called.")
@deco("module2")
def myfunc2():
print(" myfunc2() called.")
myfunc()
myfunc2()
第八步:讓裝飾器帶 類 參數(shù)
# -*- coding:gbk -*-
'''示例8: 裝飾器帶類參數(shù)'''
class locker:
def __init__(self):
print("locker.__init__() should be not called.")
@staticmethod
def acquire():
print("locker.acquire() called.(這是靜態(tài)方法)")
@staticmethod
def release():
print(" locker.release() called.(不需要對(duì)象實(shí)例)")
def deco(cls):
'''cls 必須實(shí)現(xiàn)acquire和release靜態(tài)方法'''
def _deco(func):
def __deco():
print("before %s called [%s]." % (func.__name__, cls))
cls.acquire()
try:
return func()
finally:
cls.release()
return __deco
return _deco
@deco(locker)
def myfunc():
print(" myfunc() called.")
myfunc()
myfunc()
第九步:裝飾器帶類參數(shù),并分拆公共類到其他py文件中怎静,同時(shí)演示了對(duì)一個(gè)函數(shù)應(yīng)用多個(gè)裝飾器
# -*- coding:gbk -*-
'''mylocker.py: 公共類 for 示例9.py'''
class mylocker:
def __init__(self):
print("mylocker.__init__() called.")
@staticmethod
def acquire():
print("mylocker.acquire() called.")
@staticmethod
def unlock():
print(" mylocker.unlock() called.")
class lockerex(mylocker):
@staticmethod
def acquire():
print("lockerex.acquire() called.")
@staticmethod
def unlock():
print(" lockerex.unlock() called.")
def lockhelper(cls):
'''cls 必須實(shí)現(xiàn)acquire和release靜態(tài)方法'''
def _deco(func):
def __deco(*args, **kwargs):
print("before %s called." % func.__name__)
cls.acquire()
try:
return func(*args, **kwargs)
finally:
cls.unlock()
return __deco
return _deco
# -*- coding:gbk -*-
'''示例9: 裝飾器帶類參數(shù)邮弹,并分拆公共類到其他py文件中
同時(shí)演示了對(duì)一個(gè)函數(shù)應(yīng)用多個(gè)裝飾器'''
from mylocker import *
class example:
@lockhelper(mylocker)
def myfunc(self):
print(" myfunc() called.")
@lockhelper(mylocker)
@lockhelper(lockerex)
def myfunc2(self, a, b):
print(" myfunc2() called.")
return a + b
if __name__=="__main__":
a = example()
a.myfunc()
print(a.myfunc())
print(a.myfunc2(1, 2))
print(a.myfunc2(3, 4))
FROM http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html