Data Classes in Python

Data Classes in Python

Data classes, introduced in Python 3.7, provide a decorator and functions to automatically add generated special methods such as __init__() and __repr__() to user-defined classes. They were designed to reduce the boilerplate code associated with creating classes, especially ones that are used primarily to store data.

Here's how you can use data classes:

1. Basic Usage:

from dataclasses import dataclass @dataclass class Point: x: float y: float z: float = 0.0 # Default value p = Point(1.5, 2.5) print(p) # Outputs: Point(x=1.5, y=2.5, z=0.0) 

Notice that you don't have to write the __init__() or __repr__() methods, but you still get a nice representation of the object when you print it.

2. Automatically Add Ordering Methods:

You can also automatically generate ordering methods (<, <=, >, >=) by setting the order attribute to True.

@dataclass(order=True) class Point: x: float y: float 

This will allow you to compare instances of the class based on their attributes.

3. Immutable Data Classes:

By setting the frozen attribute to True, you can make the instances of your data class immutable:

@dataclass(frozen=True) class ImmutablePoint: x: float y: float p = ImmutablePoint(1.5, 2.5) # p.x = 3.0 # This will raise an exception because the object is immutable 

4. Default Factories for Mutable Attributes:

If you want to use mutable default values like lists or dictionaries, you should use field() and its default_factory attribute:

from dataclasses import dataclass, field from typing import List @dataclass class Student: name: str grades: List[int] = field(default_factory=list) s = Student("Alice") s.grades.append(90) print(s) # Outputs: Student(name='Alice', grades=[90]) 

Without default_factory, using a mutable default value for an attribute (like grades: List[int] = []) would be a common Python pitfall, as the same list would be shared across all instances.

5. Inheritance with Data Classes:

Data classes fully support inheritance. This means you can extend a data class and add new fields:

@dataclass class Person: name: str @dataclass class Employee(Person): emp_id: int 

Conclusion:

Data classes provide a concise and clear way to define classes, especially ones that primarily store data. They automate a lot of boilerplate code, making your classes cleaner and more Pythonic.


More Tags

namevaluecollection jenkins-email-ext xml-parsing utc sqlsrv kernel react-navigation-stack httpserver zero outlook

More Programming Guides

Other Guides

More Programming Examples