ในภาษา Python เราสามารถส่งโค้ดเป็น Parameter ไปให้ฟังก์ชันอื่นเรียก เมื่อเกิดเหตุการณ์บางอย่าง เรียกว่า Callback

การที่เราส่งโค้ดฟังก์ชันอะไรก็ได้ ไปให้คนอื่นเรียกเวลาที่เกิดเหตุการณ์อะไรสักอย่าง ทำให้เราสามารถกำหนดพฤติกรรมตอบสนองต่อเหตุการณ์นั้น ได้อย่าง Dynamic

This simple diagram made with Graphviz shows a callback function, including the application main program, a software library function and the callback function. Credit https://en.wikipedia.org/wiki/File:Callback-notitle.svg
This simple diagram made with Graphviz shows a callback function, including the application main program, a software library function and the callback function. Credit https://en.wikipedia.org/wiki/File:Callback-notitle.svg

การใช้ Callback ช่วยลดความซับซ้อนของโค้ด โดยการ Delegate งานจากโปรแกรมหลัก ออกไปยัง Callback ทำให้โค้ด Clean ขึ้น

เปรียบกับ OOP

เปรียบกับภาษาโปรแกรมมิ่งแบบ Object-Oriented ที่ไม่มีการพาส ฟังก์ชัน ในการ Implement Design Pattern เช่น Observer, Strategy และ Visitor ก็จะพาส Abstract Class/Interface ไปให้โค้ดเรียก Method ที่ตกลงกันไว้เป็นดัง Callback

ตัวอย่างการใช้ Callback

Callback มี 2 ชนิด คือ Asynchronous Callback และ Synchronous Callback เราจะพบ Callback บ่อย ๆ ในการเขียนโปรแกรม เกี่ยวกับ User Interface, การจัดการ Error, การเทรน Machine Learning, ไปจนถึงการดู Gradient ภายใน Deep Neural Network, etc.

เรามาเริ่มกันเลยดีกว่า

Open In Colab

แชร์ให้เพื่อน:

Surapong Kanoktipsatharporn on FacebookSurapong Kanoktipsatharporn on LinkedinSurapong Kanoktipsatharporn on Rss
Surapong Kanoktipsatharporn
Solutions Architect at Bua Labs
The ultimate test of your knowledge is your capacity to convey it to another.

Published by Surapong Kanoktipsatharporn

The ultimate test of your knowledge is your capacity to convey it to another.