Python Dataclass



เวลาเราสร้างคลาสไว้เก็บข้อมูลล้วน ๆ โค้ดมักซ้ำซากมาก ต้องเขียน __init__ รับทุก field แล้วกำหนด self.x = x ทีละตัว เขียน __repr__ เขียน __eq__ อีก dataclass สร้างพวกนี้ให้อัตโนมัติ

ปัญหา: คลาสข้อมูลแบบเขียนเอง

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

3 เมท็อด สำหรับคลาสที่แค่เก็บ x กับ y

แก้ด้วย @dataclass

from dataclasses import dataclass


@dataclass
class Point:
    x: int
    y: int


p = Point(3, 4)
print(p)               # Point(x=3, y=4)     ← __repr__ ให้ฟรี
print(p == Point(3, 4))# True                ← __eq__ ให้ฟรี
print(p.x, p.y)        # 3 4

แค่ประกาศ field พร้อม type hint @dataclass จัดการ __init__, __repr__, __eq__ ให้หมด

type hint (x: int) จำเป็นสำหรับ dataclass เพื่อบอกว่ามี field อะไรบ้าง (Python ไม่บังคับชนิดจริงตอนรัน แต่ต้องเขียน)

ค่า default

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    stock: int = 0
    active: bool = True


p1 = Product("กาแฟ", 45)
p2 = Product("ชา", 40, stock=100, active=False)

print(p1)   # Product(name='กาแฟ', price=45, stock=0, active=True)
print(p2)   # Product(name='ชา', price=40, stock=100, active=False)

field ที่มี default ต้องอยู่หลัง field ที่ไม่มี (เหมือนพารามิเตอร์ฟังก์ชัน)

default ที่เป็นลิสต์/dict ต้องใช้ field()

เหมือนกับดักค่า default ของฟังก์ชัน — ใช้ mutable default ตรง ๆ ไม่ได้

from dataclasses import dataclass, field


@dataclass
class Cart:
    owner: str
    items: list = field(default_factory=list)     # ถูกต้อง
    # items: list = []   ← Error!


c1 = Cart("สมชาย")
c2 = Cart("สมหญิง")
c1.items.append("นม")
print(c1.items)   # ['นม']
print(c2.items)   # []   — แยกกัน ไม่ปนกัน

เพิ่มเมท็อดได้ตามปกติ

dataclass ก็เป็นคลาสธรรมดา ใส่เมท็อดเพิ่มได้

from dataclasses import dataclass


@dataclass
class Rectangle:
    width: float
    height: float

    def area(self):
        return self.width * self.height

    @property
    def is_square(self):
        return self.width == self.height


r = Rectangle(4, 4)
print(r.area())       # 16
print(r.is_square)    # True

frozen: ทำให้แก้ไม่ได้

frozen=True ทำให้ dataclass เป็น immutable เหมือนทูเพิล เหมาะกับข้อมูลที่ไม่ควรเปลี่ยน และใช้เป็นคีย์ dict / สมาชิก set ได้

from dataclasses import dataclass


@dataclass(frozen=True)
class Coordinate:
    lat: float
    lng: float


home = Coordinate(13.75, 100.50)
# home.lat = 14.0   ← FrozenInstanceError

places = {
    Coordinate(13.75, 100.50): "กรุงเทพ",
    Coordinate(18.79, 98.98): "เชียงใหม่",
}
print(places[Coordinate(13.75, 100.50)])   # กรุงเทพ

__post_init__: ทำอะไรหลังสร้างเสร็จ

ถ้าต้องคำนวณ field เพิ่มหรือตรวจสอบข้อมูลหลัง __init__

from dataclasses import dataclass, field


@dataclass
class Order:
    price: float
    quantity: int
    total: float = field(init=False)     # ไม่รับตอนสร้าง

    def __post_init__(self):
        if self.quantity <= 0:
            raise ValueError("จำนวนต้องมากกว่า 0")
        self.total = self.price * self.quantity


o = Order(price=45, quantity=3)
print(o.total)   # 135

แปลงเป็น dict / tuple

from dataclasses import dataclass, asdict, astuple


@dataclass
class User:
    name: str
    age: int


u = User("สมชาย", 25)
print(asdict(u))    # {'name': 'สมชาย', 'age': 25}
print(astuple(u))   # ('สมชาย', 25)

สะดวกมากเวลาจะแปลงเป็น JSON

เมื่อไหร่ใช้อะไร

ต้องการใช้
เก็บข้อมูลมีโครงสร้าง + มีเมท็อดบ้าง@dataclass
เก็บข้อมูลล้วน แก้ไม่ได้ เบา ๆ@dataclass(frozen=True) หรือ NamedTuple
ข้อมูลชั่วคราว ไม่ต้องมีชนิดชัดเจนdict ธรรมดา
ต้อง validate เข้มข้น / แปลงชนิดอัตโนมัติไลบรารี pydantic

ตัวอย่างรวม: ระบบจัดการหนังสือ

from dataclasses import dataclass, field, asdict
import json


@dataclass
class Book:
    title: str
    author: str
    year: int
    tags: list = field(default_factory=list)
    read: bool = False

    def mark_read(self):
        self.read = True


library = [
    Book("Clean Code", "Robert Martin", 2008, ["programming"]),
    Book("Fluent Python", "Luciano Ramalho", 2022, ["python", "advanced"]),
]

library[0].mark_read()

# กรองเฉพาะที่ยังไม่อ่าน
unread = [b for b in library if not b.read]
for b in unread:
    print(f"ยังไม่อ่าน: {b.title} ({b.year})")

# บันทึกเป็น JSON
with open("library.json", "w", encoding="utf-8") as f:
    json.dump([asdict(b) for b in library], f, ensure_ascii=False, indent=2)

เช็คความเข้าใจก่อนข้ามบท

  • ใช้ @dataclass เพื่อลดโค้ด boilerplate ของคลาสข้อมูลได้
  • รู้ว่า default ของ list/dict ต้องใช้ field(default_factory=...)
  • ลองสร้าง dataclass สำหรับรายการสินค้า แล้วคำนวณราคารวมจากราคาและจำนวน

สรุป

  • @dataclass สร้าง __init__ __repr__ __eq__ ให้อัตโนมัติจาก field ที่ประกาศพร้อม type hint
  • ค่า default ที่เป็นลิสต์/dict ใช้ field(default_factory=list)
  • frozen=True ทำให้แก้ไม่ได้ ใช้เป็นคีย์ dict ได้
  • __post_init__ สำหรับตรวจสอบ/คำนวณเพิ่มหลังสร้าง, asdict() แปลงเป็น dict

จบช่วง OOP บทถัดไปเข้าหัวข้อขั้นกลาง เริ่มจาก iterator และ generator