do not use special method on data class
Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel,
n'hésitez pas à nous contacter.
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