程式紀錄-python修飾子用法

19 views
Skip to first unread message

win...@nyps.kh.edu.tw

unread,
Nov 15, 2018, 3:02:20 AM11/15/18
to 最新消息-健中
class decoratorWithArgument(object):
def __init__(self, arg1, arg2, arg3):
print("__init__")
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
def __call__(self, f):
print("Iinside __call__")
def wrapped_f(*args):
print("Inside wrapped_f")
print("Decorator arguments:", self.arg1, self.arg2, self.arg3)
f(*args)
print("After f(*args)")
return wrapped_f

@decoratorWithArgument("hello", "world", 42)
def sayHello(a1, a2, a3, a4):
print("sayHello arguments:", a1, a2, a3, a4)
print("After decorator")
print("Prepare to call")
sayHello("say", "hello", "argument", "list")
print("after first sayHello() call")
sayHello("a", "different", "set of", "arguments")
print("after second sayHello() call")
#先解釋這個類別
類別decoratorWithArgument繼承object
定義自己的初始化,預設要3個par並將3個par設給實體化物件的屬性
定義自己被呼叫時執行的方法,必須傳入1個function參數,呼叫__call__時return內部的
function-- wrapped_f(*args),這個函數允許輸入多個參數,此外執行被掛載的函數時相當於
執行wrapped_f時會執行剛剛傳入給__call__的function參數
#再解釋
@decoreatorWithArgument(“hello”, “world”, 42)往下
因為@decoratorWithArgument有傳入參數,所以會執行__init__做好設定後再執行__call__這
時會執行print("Iinside __call__")以及return wrapped_f,至於wrapped_f的呼叫則不會執行,
必須等到所掛載的函數真實去執行才會執行此wrapped_f
因此順序應該是
__init__

Iinside __call__
After decorator
Prepare to call
Inside wrapped_f
Decorator arguments: hello world 42
sayHello arguments: say hello argument list
After f(*args)
after first sayHello() call
Inside wrapped_f
Decorator arguments: hello world 42
sayHello arguments: a different set of arguments
After f(*args)
after second sayHello() call
Reply all
Reply to author
Forward
0 new messages