Python's built-in operations are hooks into special methods. len(x) calls x.__len__(), a == b calls a.__eq__(b), a + b calls a.__add__(b), a < b calls a.__lt__(b), and for item in x uses x.__iter__(). Define them on your class and your objects work with Python's own syntax. This is how the standard library's types do it too.
There are two ways an object turns into text. __str__ is the friendly version for users, used by print(). __repr__ is the precise version for programmers, used in the interactive shell, in lists and in debuggers; ideally it looks like the code that would recreate the object. If you only write one, write __repr__: print() falls back to it.
Without __eq__, == falls back to is, so two equal-looking objects compare unequal. With __lt__, sorted(), min() and max() work. Return the special value NotImplemented from these methods when the other object is a type you don't handle, and Python will try the other side or raise a clear TypeError.
Writing __init__, __repr__ and __eq__ for every small data class is repetitive, so the dataclasses module writes them for you. Put @dataclass above the class (a line starting with @ is a decorator; a later lesson explains them) and list the attributes with their types.
from dataclasses import dataclass, field
@dataclass
class Item:
name: str
price: float
tags: list[str] = field(default_factory=list)
def with_tax(self):
return round(self.price * 1.2, 2)
a = Item("tea", 2.5)
print(a)
print(a == Item("tea", 2.5), a.with_tax())
Prints
Item(name='tea', price=2.5, tags=[])
True 3.0
field(default_factory=list) gives each instance its own new list, avoiding the mutable default trap. @dataclass(frozen=True) makes instances immutable (assigning an attribute raises an error), which also lets them be dict keys and set items; @dataclass(order=True) adds < and friends, comparing the fields in order.
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
print(sorted([Version(2, 0), Version(1, 9), Version(1, 10)]))
print(len({Version(1, 0), Version(1, 0)}))