Using dataclasses
If you want to define a class to store information without additional methods, you can use dataclass
. In a few lines, you can define it.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
And you can use it to create an object. As you can see, it also allows you to print the point with its attributes.
p = Point(10, 20)
print(p)
# Point(x=10, y=20)
They do not really add anything new. You can write code with the same behavior as shown. But it contains a lot of boilerplate code.
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
return False
In short, dataclass
allows you to define a simple class while saving code.