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

Functions

ใช้ def ตามด้วยชื่อฟังก์ชัน, รายการพารามิเตอร์ในวงเล็บ, และเครื่องหมายโคลอน Body ของฟังก์ชันเยื้อง 4 ช่องว่าง Type hints เป็นสิ่งเสริม แต่แนะนำอย่างยิ่ง — ช่วยบอกเจตนาและเปิดใช้การวิเคราะห์แบบ static

def greet(name: str, greeting: str = "Hello") -> str:
"""Return a greeting string for the given name."""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", greeting="Hi")) # Hi, Bob!

พารามิเตอร์ที่สองมี ค่าเริ่มต้น — ผู้เรียกสามารถละเว้นได้ ค่าเริ่มต้นถูกประเมินครั้งเดียวตอนกำหนดฟังก์ชัน ไม่ใช่ตอนเรียก

Python มีพารามิเตอร์สี่ประเภท:

def demo(pos, /, normal, *, kw_only):
print(pos, normal, kw_only)
demo(1, 2, kw_only=3) # OK
demo(1, normal=2, kw_only=3) # OK
  • Positional-only (ก่อน /): ไม่สามารถส่งผ่าน keyword ได้
  • Normal: positional หรือ keyword
  • Keyword-only (หลัง *): ต้องส่งผ่าน keyword เท่านั้น

ฟังก์ชันสามารถคืนค่าหลายค่าโดยคั่นด้วยคอมมา Python จะรวมไว้ใน tuple อัตโนมัติ

def min_max(numbers: list) -> tuple:
"""Return (minimum, maximum) of a list."""
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5, 9])
print(f"min={low}, max={high}") # min=1, max=9

Tuple unpacking ทางซ้ายของการกำหนดค่าจะแจกจ่ายค่าที่คืนไปยังตัวแปรแยกกัน

Docstring คือ string literal ที่วางทันทีหลัง def ใช้บันทึกว่าฟังก์ชันทำอะไร, พารามิเตอร์, และค่าที่คืน เข้าถึงได้ผ่าน help(fn) หรือ fn.__doc__

def add(a: int, b: int) -> int:
"""Return the sum of a and b.
Args:
a: First operand.
b: Second operand.
Returns:
The integer sum.
"""
return a + b

Python ค้นหาชื่อใน scope สี่ระดับ ตามลำดับ:

  1. Local — ภายในฟังก์ชันปัจจุบัน
  2. Enclosing — ฟังก์ชันที่ครอบ (สำหรับฟังก์ชันซ้อน)
  3. Global — ระดับโมดูล
  4. Built-in — ชื่อ built-in ของ Python (len, print ฯลฯ)
x = 10 # global
def outer():
y = 20 # enclosing
def inner():
z = 30 # local
return x + y + z # ค้นหา x จาก global, y จาก enclosing, z จาก local
return inner()
print(outer()) # 60

ใช้ global name เพื่อ rebind ตัวแปรระดับโมดูลจากภายในฟังก์ชัน ใช้ nonlocal name เพื่อ rebind ตัวแปรจาก scope ที่ครอบ (ที่ไม่ใช่ global)

def greet(name: str, greeting: str = "Hello") -> str:
"""Return a greeting string."""
return f"{greeting}, {name}!"
def min_max(numbers: list) -> tuple:
"""Return (minimum, maximum) of a list."""
return min(numbers), max(numbers)
x = 10
def outer():
y = 20
def inner():
z = 30
return x + y + z
return inner()
print(greet("Alice"))
print(greet("Bob", greeting="Hi"))
low, high = min_max([3, 1, 4, 1, 5, 9])
print(f"min={low}, max={high}")
print(f"LEGB sum: {outer()}")
def no_return():
pass
result = no_return()
print(f"no_return() gives: {result}")
ฟังก์ชัน Python คืนค่าอะไรถ้าไม่มี `return` statement?
ให้ `def f(a, b=5): ...`, การเรียกใดถูกต้อง?
ใน LEGB rule, 'E' ย่อมาจากอะไร?
ผลลัพธ์ของ `low, high = min_max([3, 1, 4])` คืออะไร?