Home
Python
dataclass Attribute Example (dataclasses)
Updated Apr 24, 2024
Dot Net Perls
Dataclass. By default, classes in Python do not have useful constructors or support for the print method. But with the dataclass attribute, we can automatically have this logic added.
class
With an import statement, and a decorator before the class definition, we can make classes more usable. An init() method is added, and support for repr (which prints field values) is inserted.
Example. This example program shows a class that uses the dataclass decorator, and one that does not use it. This shows us the additional features gained by using dataclasses.
Version 1 This class (Bird) has the dataclass decoration. We can pass arguments to its constructor, and print() prints the fields.
print
Version 2 Unfortunately this class (Cat) is not a dataclass, so it lacks the useful features that the other class has.
from dataclasses import dataclass @dataclass class Bird: color: str feathers: int class Cat: name: str color: int # Version 1: use data class and pass arguments to generated init method. bird = Bird("blue", 5022) print(bird) # Version 2: use normal Python class, which has no data class features. cat = Cat() print(cat)
Bird(color='blue', feathers=5022) <__main__.Cat object at 0x000001A6E8C55E20>
Asdict, astuple. It is possible to convert classes to dictionaries or tuples with the dataclasses module. The asdict() and astuple() methods are available here.
Step 1 We create a new instance of the dataclass "Snake" with its generated init() method.
Step 2 We pass the class instance to the dataclasses.asdict method to get a dictionary that contains its field names as keys.
Dictionary
Step 3 Similar to asdict, the astuple() method returns a tuple containing the values of the class (the key names are not included).
Tuple
import dataclasses @dataclasses.dataclass class Snake: color: str venom: bool # Step 1: create new instance of data class. snake = Snake("green", False) print(snake) # Step 2: convert the dataclass to a dictionary and print it. print(dataclasses.asdict(snake)) # Step 3: convert the dataclass to a tuple. print(dataclasses.astuple(snake))
Snake(color='green', venom=False) {'color': 'green', 'venom': False} ('green', False)
The dataclasses module in Python automatically generates useful methods to support constructors (init) and print (repr). This reduces the size of Python programs that need these class features.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 24, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen