Sling Academy
Home/Python/How to Use Dataclass Methods in Python

How to Use Dataclass Methods in Python

Last updated: March 01, 2023

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:

MethodDescript
__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!

Next Article: How to Use Inheritance with Dataclass in Python

Previous Article: Python: Defining Fields in Dataclass

Series: Working with Dataclasses in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types