Functions and Objects · Objects · lesson 10 of 10
Dataclasses
about 14 minutes · free · runs in your browser
When the class is just data
Writing __init__, __repr__ and __eq__ by hand for a class that only holds
values is tedious. @dataclass writes them for you:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(p) # Point(x=1, y=2)
Point(1, 2) == Point(1, 2) # True
The x: int lines are annotations. Python does not enforce them — passing a string
still works — but the decorator uses them to know which fields exist, and they document
your intent.
Fields can have defaults, and a dataclass can still have ordinary methods:
@dataclass
class Product:
name: str
price: float
quantity: int = 1
def total(self):
return self.price * self.quantity
Your turn: write that Product dataclass, with a total() method and a
discounted(percent) method returning the total with that percentage taken off, rounded
to two decimal places.
You start from this, and edit it in the browser:
from dataclasses import dataclass
@dataclass
class Product:
# Declare name, price and quantity (defaulting to 1).
pass