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.
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.
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.
class
(Bird) has the dataclass
decoration. We can pass arguments to its constructor, and print()
prints the fields.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>
It is possible to convert classes to dictionaries or tuples with the dataclasses module. The asdict()
and astuple()
methods are available here.
dataclass
"Snake" with its generated init()
method.class
instance to the dataclasses.asdict
method to get a dictionary that contains its field names as keys.astuple()
method returns a tuple containing the values of the class
(the key names are not included).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.