Hello world!

Python

[Python] dataclass 모듈

xyz1 2022. 4. 18. 17:28

dataclass 는 파이썬 3.7버전에 추가된 기능이다. https://docs.python.org/3.7/library/dataclasses.html

 

사용목적: 편리성과 직관성을 제공해준다.

 

어떠한 편리성과 직관성인지에 대해 아래 코드 예제들을 통해 살펴보도록 하자.

 

#dataclass 를 사용하지 않았을 경우

class Book:
    def __init__(self, name: str, weight: float, shelf_id:int = 0):
        self.name = name
        self.weight = weight 
        self.shelf_id = shelf_id
        
test = Book('I need Python',1.5,1267)
print(test)
>>> <__main__.Book object at 0x0000014020474DC8>

 

#@dataclass를 사용했을 경우

from dataclasses import dataclass

@dataclass
class Book:
    name: str
    weight: float
    shelf_id: int = 0

test = Book('I need Python',1.5,1267)
print(test)
>>> Book(name='I need Python', weight=1.5, shelf_id=1267)

@dataclass를 사용했을 경우 코드가 간결해진 것을 볼 수 있다. 즉 기존의 class의 번거롭던 작업(코드)들을 자동으로 생성해주는 모듈이다. 

 

자세한 내용: https://docs.python.org/3.7/library/dataclasses.html

 

dataclasses — 데이터 클래스 — Python 3.7.13 문서

이 모듈은 __init__() 나 __repr__() 과 같은 생성된 특수 메서드 를 사용자 정의 클래스에 자동으로 추가하는 데코레이터와 함수를 제공합니다. 원래 PEP 557 에 설명되어 있습니다. 생성된 메서드에서

docs.python.org

개발자들은 항상 공식문서인 python.org에 들어가서 지식을 습득해야한다.