บทที่ 3.2: อาร์กิวเมนต์ยืดหยุ่น ขอบเขตตัวแปร และ Lambda (Args, Kwargs, Scope & Lambda)
เอกสารนี้อธิบายการจัดการพารามิเตอร์แบบยืดหยุ่นด้วย *args และ **kwargs ลำดับการเรียงพารามิเตอร์ ขอบเขตตัวแปรตามกฎ LEGB การใช้คำสั่ง global และ nonlocal รวมถึงการสร้าง Anonymous Function ด้วย lambda
1. อาร์กิวเมนต์แบบไม่จำกัดจำนวน (*args และ **kwargs)
ในกรณีที่ไม่ทราบจำนวนข้อมูลที่จะส่งเข้ามาในฟังก์ชันล่วงหน้า สามารถใช้ *args และ **kwargs เพื่อรับค่าได้อย่างยืดหยุ่น
1.1 Positional Arguments แบบไม่จำกัดจำนวน (*args)
รับค่าอาร์กิวเมนต์แบบไม่ระบุชื่อเข้ามาเป็น Tuple
def sum_all(*args):
# args จะมีประเภทเป็น tuple
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # Output: 6
print(sum_all(10, 20, 30, 40)) # Output: 100
1.2 Keyword Arguments แบบไม่จำกัดจำนวน (**kwargs)
รับค่าอาร์กิวเมนต์แบบระบุชื่อเข้ามาเป็น Dictionary
def print_user_profile(**kwargs):
# kwargs จะมีประเภทเป็น dict
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_profile(name="Alex", age=25, city="Bangkok")
# Output:
# name: Alex
# age: 25
# city: Bangkok
1.3 ลำดับการเรียงตำแหน่งพารามิเตอร์ (Parameter Ordering)
เมื่อต้องใช้งานพารามิเตอร์หลายชนิดร่วมกันในฟังก์ชันเดียว ต้องเรียงลำดับดังนี้:
1. Standard Arguments
2. *args
3. Default Arguments
4. **kwargs
2. ขอบเขตตัวแปร และกฎ LEGB (Variable Scope & LEGB Rule)
การค้นหาและเข้าถึงค่าของตัวแปรใน Python จะอิงตามลำดับ LEGB Rule:
- L (Local): ตัวแปรที่ประกาศภายในฟังก์ชันปัจจุบัน
- E (Enclosing): ตัวแปรในฟังก์ชันภายนอกที่ครอบฟังก์ชันอื่นอยู่ (Nested Functions)
- G (Global): ตัวแปรที่ประกาศในระดับบนสุดของไฟล์ (Module-level)
- B (Built-in): คีย์เวิร์ดหรือฟังก์ชันที่มาพร้อมกับภาษา Python (เช่น
len,print)
2.1 การแก้ไขตัวแปรด้วย global และ nonlocal
หากต้องการ แก้ไขค่า ตัวแปรรูปแบบ Global หรือ Enclosing จากภายใน Local Scope ต้องระบุคีย์เวิร์ดแจ้งระบบชัดเจน
# 1. การใช้ global
count = 0
def increment():
global count
count += 1 # แก้ไขตัวแปร count ใน Global Scope
increment()
print(count) # Output: 1
# 2. การใช้ nonlocal
def outer():
x = 10
def inner():
nonlocal x
x += 5 # แก้ไขตัวแปร x ใน Enclosing Scope ของ outer()
inner()
print(x) # Output: 15
outer()
3. ฟังก์ชันแบบไม่ระบุชื่อ (Lambda Functions)
lambda คือฟังก์ชันขนาดสั้นแบบไม่มีชื่อ (Anonymous Function) นิยมใช้กับการประมวลผลสั้นๆ ที่มีนิพจน์เพียงบรรทัดเดียว
3.1 ไวยากรณ์
lambda arguments: expression
# ฟังก์ชันปกติ
def add_five(x):
return x + 5
# เขียนด้วย Lambda
add_five_lambda = lambda x: x + 5
print(add_five_lambda(10)) # Output: 15
3.2 การนำ Lambda ไปใช้ร่วมกับ map() และ filter()
numbers = [1, 2, 3, 4, 5, 6]
# map(): นำฟังก์ชันไปประมวลผลกับสมาชิกทุกตัว
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25, 36]
# filter(): กรองเอาเฉพาะสมาชิกที่ผ่านเงื่อนไข (คืนค่า True)
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4, 6]