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

Functions

คุณรู้จักฟังก์ชันฝั่ง TypeScript ดีอยู่แล้ว คีย์เวิร์ด def ของ Python เทียบกับการประกาศ function ของ TS ได้แทบตรงตัว แนวคิดเดียวกัน ต่างกันแค่ syntax เล็กน้อย

จุดที่ Python ต่างออกไปจริง ๆ คือระบบ keyword arguments และการ return หลายค่าได้สะอาด ๆ ผ่าน tuple unpacking

TypeScript
// TypeScript
function 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
Python
# Python
def 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

Python ให้ฝั่งที่เรียกระบุชื่อ argument ตัวไหนก็ได้ ณ จุดเรียก โดยไม่ต้องสนลำดับ ต่างจาก TypeScript ที่ต้องพึ่งท่า object destructuring เพราะใน Python ทุกพารามิเตอร์ส่งด้วยชื่อได้อยู่แล้วโดยธรรมชาติ

TypeScript
// TypeScript — must use object destructuring to name args
function createUser({
name,
role = "viewer",
active = true,
}: {
name: string;
role?: string;
active?: boolean;
}) {
console.log(`${name} (${role}), active=${active}`);
}
createUser({ name: "Alice", role: "admin" });
Python
# Python — every parameter is callable by name
def create_user(name: str, role: str = "viewer", active: bool = True) -> None:
print(f"{name} ({role}), active={active}")
# Positional call
create_user("Alice", "admin")
# Keyword call — order does not matter
create_user(role="admin", name="Alice")
# Mix positional and keyword
create_user("Bob", active=False)

*args รวบ positional argument ที่เกินมาใส่ tuple ส่วน **kwargs รวบ keyword argument ที่เกินมาใส่ dict ใช้คู่กันเมื่อไหร่ก็ออกแบบ API ให้ยืดหยุ่นได้ทันที

TypeScript
// TypeScript
function sum(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
// No clean native equivalent for named variadic args
function 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)); // 10
logFields({ lang: "Python", tier: "backend" });
Python
# Python *args and **kwargs
def 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.0
log_fields(lang="Python", tier="backend")

TypeScript ใช้ destructuring บน array หรือ object ส่วน Python ใช้ tuple unpacking คือฟังก์ชัน return tuple ออกมา แล้วคุณ unpack ตรงจุดเรียกได้เลย ท่านี้ให้ความรู้สึกเป็นฟีเจอร์ first-class ของภาษา ไม่ใช่ทางเลี่ยงที่หาทางออกไม่ได้

TypeScript
// TypeScript — return an object or array
function 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
# Python — return a tuple, unpack at the call site
def 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 tuple
result = 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")
Python ใช้คีย์เวิร์ดอะไรในการนิยามฟังก์ชัน?
ใน Python การเรียก `greet(name="Alice", greeting="Hey")` ทั้งที่ประกาศ `def greet(greeting, name)` ใช้ได้เพราะ:
`**kwargs` รวบอะไรเข้าไปภายในฟังก์ชัน Python?
`def divmod_custom(a, b): return a // b, a % b` return อะไรออกมา?