學會了新招 python decorator

參考文章:

1. 基礎: 不帶參數 -->  http://blog.roodo.com/descriptor/archives/9206319.html

2. 進階: 帶參數 --> http://blog.roodo.com/descriptor/archives/9424561.html

自己實作的範例:


class myDecorator(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
print "Entering", self.f.__name__
print args[0]
self.f(*args)
print "Exited", self.f.__name__

注意定義decorator 時必須要定義好兩個 method, 一個是 __init__ , 另一個是 __call__
當初始化時會用到, 而__call__  是當函式被呼叫時會被啟動

以上例來說:  當初始化時(應該是定義function 時), 該decorator 的 f 屬性(self.f )會被指派給傳入的函式(f), 也就是說, 當我們在宣告函式時指定要用decorator, 該函式就會傳入該decorator, 當被呼叫到時, 該decorator 就可以用 self.f 來呼叫這個函式, 以上例來說, 我們在 __call__ 裡面寫了 self.f(*args) 就是說, 把decorator 收到的參數tuple(*args) 直接傳入函式, 當然你也可以不那麼做, 例如 args[0] 就是只取傳入函式的第一個參數, 如果改寫一下, 變成: self.f(args[0]) 則就是只傳入第一個參數給函式

當然啦, 你也可以將myDecorator 接收的參數改成不那麼彈性


class myDecorator(object):
def __init__(self, f):
self.f = f
def __call__(self, x):
print "Entering", self.f.__name__
print x
print "Exited", self.f.__name__

例如上例就是限定當函式被呼叫時, 只能接收一個參數(超過時會引發參數數量不正確之 error )



留言

熱門文章