ข้ามไปยังเนื้อหา

เจาะลึกเรื่อง Function

ใน Python นั้น function คือค่า (value) ตัวหนึ่ง ไม่ใช่ syntax พิเศษ และไม่ใช่ของชั้นรอง เราสามารถกำหนด function ให้กับตัวแปร เก็บไว้ใน list ส่งเป็น argument หรือ return ออกมาจากอีก function หนึ่งได้ คุณสมบัตินี้เรียกว่าสถานะ first-class ที่เป็นรากฐานของทุก pattern ขั้นสูงในโมดูลนี้

def greet(name: str) -> str:
return f"Hello, {name}!"
# Assign to a variable
say_hi = greet
# Pass as an argument
def apply(fn, value):
return fn(value)
result = apply(greet, "Python")
print(result) # Hello, Python!

เนื่องจาก greet เป็นแค่ object ตัวหนึ่ง say_hi และ greet จึงชี้ไปยัง function ตัวเดียวกัน การเรียก say_hi("World") จึงเหมือนกับการเรียก greet("World") ทุกประการ

บทเรียนแนวคิดหลัก
Args & Kwargsparameter แบบ positional, keyword, variadic และ keyword-only
Closuresnested function, free variable และ nonlocal
Decoratorsfunction ที่ห่อ function อื่น; functools.wraps
Generatorsyield, lazy evaluation และ StopIteration

แต่ละบทเรียนนั้นจบในตัวเอง และต่อยอดจากรากฐานนี้ นั่นคือ function เป็น object ที่เราจัดการได้อย่างอิสระ

โค้ดด้านล่างแสดงสองแนวคิดหลักพร้อมกัน ได้แก่ การส่ง function เป็น argument และการ return function เป็นค่ากลับมา

def make_multiplier(factor: int):
def multiply(x: int) -> int:
return x * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
numbers = [1, 2, 3, 4, 5]
doubled = list(map(double, numbers))
tripled = list(map(triple, numbers))
print("doubled:", doubled)
print("tripled:", tripled)
# Functions are objects — we can store them in a list
ops = [double, triple, make_multiplier(10)]
for op in ops:
print(op(7))
คำว่า 'first-class function' ใน Python หมายความว่าอย่างไร?
Built-in function ตัวใดที่รับ function และ iterable เป็น argument?
หลังจากเขียน `f = greet` แล้ว ข้อใดถูกต้อง?