이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

Metadata

ID: python-best-practices/dataclass-special-methods

Language: Python

Severity: Notice

Category: Best Practices

Description

Data classes (annotated with @dataclass) do not use special methods, such as __init__, __gt__, and others.

Non-Compliant Code Examples

@dataclass
class _Leaf(Generic[T]):
    parent: _Leaf
    value: T

    def __init__(self, value: Optional[T] = None):
        self.value = value
        self.parent = self

    def update(self, value: T):
        self.value = value
        return self

    def __lt__(self, other: _Leaf):
        return repr(self) < repr(other)

    def __gt__(self, other: _Leaf):
        return repr(self) > repr(other)

    # __eq__ should not be used
    def __eq__(self, other: _Leaf):
        return repr(self) == repr(other)

    def __repr__(self):
        return self.value

Compliant Code Examples

@dataclass
class _Leaf(Generic[T]):
    parent: _Leaf
    value: T

    def update(self, value: T):
        self.value = value
        return self

    def __repr__(self):
        return self.value
PREVIEWING: brett.blue/embedded-collector-release