Open Pin-Jiun opened 1 year ago
透過參數傳遞函式到另外一個函式中 將function當作parameter傳遞的行為
def test(arg): print(arg) def handle(): print(100) #將handle()這個function當作參數傳遞:callback function test(handle)
會印出handle()這個function的記憶體位置
<function handle at 0x02181978>
arg此時會變成function的記憶體位置, 要使用的話加入()變成呼叫function 也就是callback handle() 這個function
()
def test(arg): arg()#callback function def handle(): print(100) test(handle)
100
再進階, 修改成可以傳遞parameter的callback function
def test(arg): arg(60)#callback function def handle(x): print(x) test(handle)
60
實際應用例子
def add(n1, n2, cb_f): cb_f(n1+n2) def handle1(result): print("兩數相加結果為", result) def handle2(result): print("n1 add n2, result is", result) add(3, 4, handle1) add(3, 4, handle2)
Callback Function
透過參數傳遞函式到另外一個函式中 將function當作parameter傳遞的行為
會印出handle()這個function的記憶體位置
arg此時會變成function的記憶體位置, 要使用的話加入
()
變成呼叫function 也就是callback handle() 這個function再進階, 修改成可以傳遞parameter的callback function
實際應用例子