Python Functions สามารถคืนค่าหลายค่าได้โดยตรง เก็บในตัวแปรหลายตัวพร้อมกัน นี่คือ Default Property ของ Python ที่หลายภาษา (C++, Java) ไม่มีโดยตรง
วิธีที่ 1: Tuple (Implicit) - แนะนำสำหรับค่าน้อย
def func(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** 3
return y0, y1, y2 # Implicit Tuple
# เรียกใช้
a, b, c = func(2)
print(a, b, c) # 3 6 27
# หรือเก็บเป็น Tuple
result = func(2)
print(result[0], result[1], result[2])
วิธีที่ 2: Dictionary - เหมาะสำหรับค่ามาก/ชื่อมีความหมาย
def func(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** 3
return {'y0': y0, 'y1': y1, 'y2': y2}
result = func(2)
print(result['y1']) # 6 - เข้าถึงโดยชื่อ ชัดเจนกว่า Index
วิธีที่ 3: Class / Named Tuple / Dataclass - โครงสร้างชัดเจน
from dataclasses import dataclass
from typing import NamedTuple
# NamedTuple (Immutable, Lightweight)
class Result(NamedTuple):
y0: int
y1: int
y2: int
# Dataclass (Mutable, Feature-rich - Python 3.7+)
@dataclass
class ResultDC:
y0: int
y1: int
y2: int
def func_namedtuple(x):
return Result(x+1, x*3, (x+1)**3)
def func_dataclass(x):
return ResultDC(x+1, x*3, (x+1)**3)
r1 = func_namedtuple(2)
print(r1.y0, r1.y1, r1.y2) # 3 6 27
r2 = func_dataclass(2)
print(r2.y0, r2.y1, r2.y2)
วิธีที่ 4: List - Mutable Sequence
def func(x):
result = [x + 1]
result.append(x * 3)
result.append((x + 1) ** 3)
return result
# เรียกใช้
vals = func(2)
print(vals) # [3, 6, 27]
วิธีที่ 5: Generator (yield) - สำหรับค่ามากมาย/Infinite
def func(x):
y0 = x + 1
yield y0
yield x * 3
yield y0 ** 3
# ใช้งาน
gen = func(2)
print(next(gen)) # 3
print(next(gen)) # 6
print(next(gen)) # 27
# หรือ Loop
for val in func(2):
print(val)
เปรียบเทียบและเลือกใช้
| Method | Best For | Pros | Cons |
|---|---|---|---|
| Tuple | 2-5 ค่า, Fixed, Simple | Simple, Fast, Unpacking ใส่ใจ | ลืมลำดับง่าย ถ้าค่ามาก |
| Dict | ค่ามาก, Key มีความหมาย | เข้าถึงด้วยชื่อ, Readable | Overhead มากกว่า Tuple |
| NamedTuple | Immutable Struct | Type Hints, Attribute Access, Immutable | Immutable |
| Dataclass | Complex Data, Methods | Full Features, Mutable, Type Hints | Verbose |
| List | Mutable Sequence | Append/Pop ได้ | ไม่ Self-documenting |
| Generator | Large/Infinite Sequence | Memory Efficient, Lazy | One-time Iteration |
Best Practice
- 2-3 ค่า: Tuple + Unpacking
a, b, c = func() - >3 ค่า หรือ Key มีความหมาย: Dictionary หรือ NamedTuple/Dataclass
- Stream/Infinite: Generator (
yield) - หลีกเลี่ยง List เว้นแต่ต้อง Mutate ผลลัพธ์