https://docs.python.org/3/tutorial/classes.html#odds-and-ends
- 간단한 레코드/구조체처럼 필드만 묶고 싶다면 @dataclass 사용이 관용적입니다.
- 타입 힌트와 함께 선언하면 생성자/표시/비교 등을 자동 생성합니다.
from dataclasses import dataclass, field
@dataclass(order=True, slots=True)
class Book:
title: str
author: str
price: float
tags: list[str] = field(default_factory=list, repr=False) # repr에서 제외
id: int = field(init=False, compare=False) # 생성자 인자 제외, 비교에도 제외
def __post_init__(self):
# __init__ 끝난 뒤 추가 초기화
object.__setattr__(self, "id", hash((self.title, self.author)))
b1 = Book("파이썬", "홍길동", 10.0, tags=["python"])
b2 = Book("파이썬", "홍길동", 12.0)
print(b1) # Book(title='파이썬', author='홍길동', price=10.0)
print(b1 == b2) # True (order=True로 비교s 메서드 생성, tags/id는 비교
제외)
print(b1 < b2) # True (price 기준 튜플 비교: (title, author,
price, ...))
print(b1.id) # 해시로 생성된 고유 id
print(b1.tags) # ['python']- init 자동 생성: title, author, price, tags만 인자로 받음(id는 init=False라 제외).
- repr 자동 생성: tags는 repr=False라 출력에서 숨김.
- 비교 메서드 생성: order=True로 <, ⇐, >, >=까지 생성. compare=False인 필드는 비교에 제외.
- default_factory=list로 인스턴스별 새 리스트 제공(공유 방지).
- slots=True로 slots 생성해 메모리 절약/속성 제한.
__post_init__에서 추가 초기화(여기서는 id 설정). frozen=True였다면object.__setattr__를 써야 재할당 가능.