Functions
Functions: def แทน function
หัวข้อที่มีชื่อว่า “Functions: def แทน function”คุณรู้จักฟังก์ชันฝั่ง TypeScript ดีอยู่แล้ว คีย์เวิร์ด def ของ Python เทียบกับการประกาศ function ของ TS ได้แทบตรงตัว แนวคิดเดียวกัน ต่างกันแค่ syntax เล็กน้อย
จุดที่ Python ต่างออกไปจริง ๆ คือระบบ keyword arguments และการ return หลายค่าได้สะอาด ๆ ผ่าน tuple unpacking
การนิยามฟังก์ชันพื้นฐาน
หัวข้อที่มีชื่อว่า “การนิยามฟังก์ชันพื้นฐาน”// TypeScriptfunction greet(name: string, greeting: string = "Hello"): string { return `${greeting}, ${name}!`;}
const add = (a: number, b: number): number => a + b;
console.log(greet("Alice")); // Hello, Alice!console.log(greet("Bob", "Hi")); // Hi, Bob!console.log(add(3, 4)); // 7# Pythondef greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}!"
def add(a: int, b: int) -> int: return a + b
print(greet("Alice")) # Hello, Alice!print(greet("Bob", "Hi")) # Hi, Bob!print(add(3, 4)) # 7ความต่างสำคัญที่ควรสังเกต:
- ใช้คีย์เวิร์ด
defแทนfunction - annotation ของ return type อยู่หลัง
->แทน: ReturnType - ไม่มีปีกกา — เนื้อของฟังก์ชันใช้การย่อหน้า
- ไม่มี semicolon
Keyword arguments
หัวข้อที่มีชื่อว่า “Keyword arguments”Python ให้ฝั่งที่เรียกระบุชื่อ argument ตัวไหนก็ได้ ณ จุดเรียก โดยไม่ต้องสนลำดับ ต่างจาก TypeScript ที่ต้องพึ่งท่า object destructuring เพราะใน Python ทุกพารามิเตอร์ส่งด้วยชื่อได้อยู่แล้วโดยธรรมชาติ
// TypeScript — must use object destructuring to name argsfunction createUser({ name, role = "viewer", active = true,}: { name: string; role?: string; active?: boolean;}) { console.log(`${name} (${role}), active=${active}`);}
createUser({ name: "Alice", role: "admin" });# Python — every parameter is callable by namedef create_user(name: str, role: str = "viewer", active: bool = True) -> None: print(f"{name} ({role}), active={active}")
# Positional callcreate_user("Alice", "admin")
# Keyword call — order does not mattercreate_user(role="admin", name="Alice")
# Mix positional and keywordcreate_user("Bob", active=False)*args และ **kwargs: argument แบบ variadic
หัวข้อที่มีชื่อว่า “*args และ **kwargs: argument แบบ variadic”*args รวบ positional argument ที่เกินมาใส่ tuple ส่วน **kwargs รวบ keyword argument ที่เกินมาใส่ dict ใช้คู่กันเมื่อไหร่ก็ออกแบบ API ให้ยืดหยุ่นได้ทันที
// TypeScriptfunction sum(...numbers: number[]): number { return numbers.reduce((a, b) => a + b, 0);}
// No clean native equivalent for named variadic argsfunction logFields(fields: Record<string, string>): void { for (const [k, v] of Object.entries(fields)) { console.log(`${k}: ${v}`); }}
console.log(sum(1, 2, 3, 4)); // 10logFields({ lang: "Python", tier: "backend" });# Python *args and **kwargsdef total(*numbers: float) -> float: return sum(numbers)
def log_fields(**fields: str) -> None: for key, value in fields.items(): print(f"{key}: {value}")
print(total(1, 2, 3, 4)) # 10.0log_fields(lang="Python", tier="backend")การ return หลายค่า
หัวข้อที่มีชื่อว่า “การ return หลายค่า”TypeScript ใช้ destructuring บน array หรือ object ส่วน Python ใช้ tuple unpacking คือฟังก์ชัน return tuple ออกมา แล้วคุณ unpack ตรงจุดเรียกได้เลย ท่านี้ให้ความรู้สึกเป็นฟีเจอร์ first-class ของภาษา ไม่ใช่ทางเลี่ยงที่หาทางออกไม่ได้
// TypeScript — return an object or arrayfunction minMax(nums: number[]): { min: number; max: number } { return { min: Math.min(...nums), max: Math.max(...nums) };}
const { min, max } = minMax([3, 1, 4, 1, 5, 9]);console.log(min, max); // 1 9# Python — return a tuple, unpack at the call sitedef min_max(nums: list[float]) -> tuple[float, float]: return min(nums), max(nums)
low, high = min_max([3, 1, 4, 1, 5, 9])print(low, high) # 1 9
# Or keep it as a tupleresult = min_max([3, 1, 4, 1, 5, 9])print(result) # (1, 9)ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”def greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}!"
def stats(*numbers: float) -> tuple[float, float]: return min(numbers), max(numbers)
def describe(**info: str) -> None: for key, value in info.items(): print(f" {key}: {value}")
print(greet("Alice"))print(greet("Bob", greeting="Hi"))print(greet(name="Carol", greeting="Hey"))
low, high = stats(3, 1, 4, 1, 5, 9, 2, 6)print(f"min={low}, max={high}")
print("User info:")describe(language="Python", version="3.12", tier="backend")Loading Python runtime (first run only)…