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) # OKdemo(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=9Tuple unpacking ทางซ้ายของการกำหนดค่าจะแจกจ่ายค่าที่คืนไปยังตัวแปรแยกกัน
Docstrings
หัวข้อที่มีชื่อว่า “Docstrings”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กฎ LEGB Scope
หัวข้อที่มีชื่อว่า “กฎ LEGB Scope”Python ค้นหาชื่อใน scope สี่ระดับ ตามลำดับ:
- Local — ภายในฟังก์ชันปัจจุบัน
- Enclosing — ฟังก์ชันที่ครอบ (สำหรับฟังก์ชันซ้อน)
- Global — ระดับโมดูล
- 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)
Demo ที่รันได้จริง
หัวข้อที่มีชื่อว่า “Demo ที่รันได้จริง”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}")Loading Python runtime (first run only)…