반응형
- 데이터 값을 보유하도록 설계된 클래스
- 파이썬 3.7에 도입된 파이썬 내장 라이브러리
- 사용예시:
dataclass는 다음과 같이 정의한다. 필드를 정의할 때 타입 힌트를 필수적으로 추가한다.
from dataclasses import dataclass
@dataclass
class Series:
title: str
seasons: int
genre: list[str]
main_cast: list[str]
summary: str
dataclass는 다음과 같이 초기화할 수 있다.
# 초기화 방법 1
series1 = Series(
title="How I Met Your Mother",
seasons=9,
genre=["Comedy", "Romance"],
main_cast=["Josh Radnor", "Jason Segel", "Cobie Smulders", "Neil Patrick Harris", "Alyson Hannigan"],
summary="The series follows the main character, Ted Mosby, and his group of friends in New York City's Manhattan. As a framing device, Ted, in the year 2030, recounts to his son and daughter the events that led him to meet their mother."
)
# 초기화 방법 2
data = {
"title": "How I Met Your Mother",
"seasons": 9,
"genre": ["Comedy", "Romance"],
"main_cast": ["Josh Radnor", "Jason Segel", "Cobie Smulders", "Neil Patrick Harris", "Alyson Hannigan"],
"summary": "The series follows the main character, Ted Mosby, and his group of friends in New York City's Manhattan. As a framing device, Ted, in the year 2030, recounts to his son and daughter the events that led him to meet their mother."
}
series2 = Series(**data)
# 초기화 방법 3
data_list = [
"How I Met Your Mother",
9,
["Comedy", "Romance"],
["Josh Radnor", "Jason Segel", "Cobie Smulders", "Neil Patrick Harris", "Alyson Hannigan"],
"The series follows the main character, Ted Mosby, and his group of friends in New York City's Manhattan. As a framing device, Ted, in the year 2030, recounts to his son and daughter the events that led him to meet their mother."
]
series3 = Series(*data_list)
dataclass는 자동으로 __eq__ 메서드를 제공한다.
- __eq__ 메서드는 클래스의 인스턴스 간의 동등성(equality)를 비교한다.
dataclass는 자동으로 __repr__ 메서드를 제공한다.
- __repr__ 메서드는 객체를 문자열로 표현한다.
dataclass에는 메서드를 자유롭게 추가할 수 있다.
@dataclass
class Series:
title: str
seasons: int
genre: list[str]
main_cast: list[str]
summary: str
def get_main_cast(self) -> list[str]:
return self.main_cast
dataclass의 필드에는 기본값을 추가할 수 있다.
@dataclass
class Series:
title: str
genre: list[str]
main_cast: list[str]
seasons: int = 1
summary: str = "Not provided"
field() 지정자로 dataclass의 각 필드로 개별적으로 사용자 지정할 수 있다.
from dataclasses import dataclass, field
@dataclass
class Series:
title: str
genre: list[str]
main_cast: list[str]
seasons: int = field(default=1, metadata={'description': 'Number of seasons'})
summary: str = field(default="Not provided", metadata={'description': 'Brief summary of the series'})
field()가 지원하는 파라미터는 다음과 같다.
default | 필드의 기본값 지정 |
default_factory | 필드의 초기값을 반환 |
init | init 메서드에서 필드를 사용 |
repr | 객체의 repr에서 필드를 사용 |
compare | 비교할때 필드를 포함 |
hash | hash() 계산 시 필드를 포함 |
metadata | 필드에 대한 정보를 포함하는 매핑 |
@dataclass() 데코레이터에 매개변수를 줄 수 있다.
from dataclasses import dataclass
@dataclass(order=True)
class PlayingCard:
rank: str
suit: str
card1 = PlayingCard(rank='10', suit='♠')
card2 = PlayingCard(rank='A', suit='♠')
print(card1 < card2) # True, '10' 보다 'A'가 더 크다고 가정합니다.
print(card1 > card2) # False
@dataclass() 데코레이터에서 지원하는 매개변수들은 다음과 같다.
init | 데이터 클래스에 init 메서드를 생성할지 결정. 기본 값은 True로 기본적으로 init 메서드 생성. |
repr | 데이터 클래스에 repr 메서드를 생성할지 결정. 기본 값은 True. |
eq | 데이터 클래스에 eq 메서드를 생성할지 결정. 기본 값은 True. |
order | 데이터 클래스의 인스턴스 간의 순서 비교를 가능하게 함 |
unsafe_hash | 강제로 __hash__() 메서드를 생성. unsafe_hash=True이면, 데이터 클래스의 인스턴스가 수정 가능하더라 __hash__ 메서드를 강제로 생성하므로, unsafe가 붙었음. |
frozen | True로 설정하면 데이터 클래스의 인스턴스를 불변(immutable)로 만듦. 이때, 필드 값을 변경하면 AttributeError 발생. |
참고자료
https://realpython.com/python-data-classes/
반응형
댓글