Home
Map
dataclass Attribute Example (dataclasses)Use the dataclass attribute to automatically generate useful methods for classes.
Python
This page was last reviewed on Apr 24, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 24, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.