attrs

Utilities

상용구가 없는 클래스

개요 attrs

attrs(attr로 가져옴)는 상용구 없이 간결하고 올바른 Python 클래스를 작성할 수 있는 Python 패키지입니다. __init__, __repr__, __eq__ 및 기타 dunder 메서드를 자동으로 생성하고 유효성 검사기, 변환기, 슬롯 및 고정(불변) 클래스를 추가로 지원합니다.

attrs는 Python에서 깔끔한 데이터 보유 클래스를 정의하는 데 널리 사용되며 Python의 내장 데이터 클래스 모듈에 직접적으로 영감을 주었습니다.PyRun에서 attrs는 micropip을 통해 즉시 로드되므로 클래스 디자인 패턴을 배울 때 탐색할 수 있는 훌륭한 라이브러리가 됩니다.

코드 및 실행 출력

attrs 유효성 검사기로 Python 클래스를 정리합니다.

Attrs Data Classes에디터에서 실행
import attr

@attr.s(auto_attribs=True)
class Point:
    x: float
    y: float

    def distance_to(self, other: "Point") -> float:
        return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5

@attr.s(auto_attribs=True)
class Polygon:
    name: str
    vertices: list = attr.Factory(list)

    def perimeter(self) -> float:
        pts = self.vertices + [self.vertices[0]]
        return sum(pts[i].distance_to(pts[i+1]) for i in range(len(pts)-1))

triangle = Polygon("Triangle", [
    Point(0, 0), Point(4, 0), Point(0, 3)
])

print(repr(triangle))
print(f"Perimeter: {triangle.perimeter():.4f}")
print(f"Expected : 12.0000  (3-4-5 right triangle)")

관련 패키지

권장 Python 리소스

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