dataclasses

Utilities

형식화된 데이터 모델

개요 dataclasses

데이터 클래스 모듈은 Python 표준 라이브러리(Python 3.7+)의 일부입니다. 주로 데이터를 저장하는 데 사용되는 클래스에 대해 __init__, __repr__, __eq__ 및 __hash__와 같은 특수 메서드를 자동으로 생성하기 위한 데코레이터와 함수를 제공합니다. 데이터 클래스는 모델을 읽기 쉽고 유지 관리하기 쉽게 유지하면서 상용구를 줄입니다.

데이터 클래스는 Python 표준 라이브러리의 일부이므로 추가 가져오기나 micropip 다운로드 없이PyRun에서 즉시 작동합니다. 이는 Python에서 구조화된 데이터 모델을 정의하는 가장 가벼운 방법이며, 객체 지향 프로그래밍을 배우거나 소규모 앱을 구축하는 데 특히 유용합니다.

코드 및 실행 출력

정렬 및 asdict 직렬화가 포함된 형식화된 모델입니다.

Python Dataclasses에디터에서 실행
from dataclasses import dataclass, field, asdict
from typing import List

@dataclass(order=True)
class Student:
    name: str
    grade: float
    subjects: List[str] = field(default_factory=list)

    def gpa_letter(self) -> str:
        if self.grade >= 90: return 'A'
        if self.grade >= 80: return 'B'
        if self.grade >= 70: return 'C'
        return 'D'

students = [
    Student("Alice",   94.5, ["Math", "Physics"]),
    Student("Bob",     78.2, ["History", "English"]),
    Student("Charlie", 88.0, ["CS", "Math", "Bio"]),
]

for s in sorted(students, reverse=True):
    print(f"{s.name:<10} GPA={s.grade:.1f} ({s.gpa_letter()}) — {', '.join(s.subjects)}")

print("\nAs dicts:")
for row in students:
    print(asdict(row))

관련 패키지

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.