The dataclasses module in Python provides a convenient way to define classes with a minimal amount of boilerplate. By adding the @dataclass decorator to a class, Python generates several default methods automatically. In this practical article, we will have a deep dive into these auto-generated methods and learn how to customize them by specifying custom implementations.
Default Dataclass Methods
The table below describes the default dataclass methods:
Method | Descript |
---|---|
__init__() | Initializes a new instance of the class. |
__repr__() | Returns a string representation of the instance. |
__eq__() | Compares two instances for equality. |
__ne__() | Compares two instances for inequality. |
__lt__() | Compares two instances to determine if one is less than the other. |
__le__() | Compares two instances to determine if one is less than or equal to the other. |
__gt__() | Compares two instances to determine if one is greater than the other. |
__ge__() | Compares two instances to determine if one is greater than or equal to the other. |
Customizing Dataclass Methods
Dataclasses also provide the ability to customize these default methods by specifying custom implementations. To do so, you can define a method with the same name as the default method in your class. For example, to customize (override) the __repr__() method, you could define a method like this:
from dataclasses import dataclass
@dataclass
class MyClass:
x: int
y: int
def __repr__(self):
return f'Hello there, MyClass(x={self.x}, y={self.y})'
my_class = MyClass(1, 2)
print(my_class)
Output:
Hello there, MyClass(x=1, y=2)
This custom implementation of __repr__() returns a greeting and a string representation of the instance that includes the values of its x and y attributes.
One More Example
This example defines a class named User with a custom equality comparison (override the __eq__() method):
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
# Compare two users by their age only
def __eq__(self, other):
if isinstance(other, User):
return self.age == other.age
return False
u1 = User("John", 20)
u2 = User("Jane", 20)
u3 = User("Jack", 30)
print(u1 == u2)
print(u1 == u3)
Output:
True
False
That’s it. Happy coding!