Overview
Let a decorator write __init__, __repr__ and comparisons for you, and keep your classes focused on what matters.
- @dataclass and typed fields
- order=True for sorting and comparisons
- @classmethod as an alternative constructor
Short Course
@dataclass reads the typed fields of a class and generates __init__,
__repr__ and __eq__. With order=True it also compares instances field
by field, in order.
from dataclasses import dataclass
@dataclass(order=True)
class Card:
rank: int
suit: str
Card(10, "hearts") # Card(rank=10, suit='hearts')
Card(2, "spades") < Card(10, "hearts") # True — compares rank first
Task
Make Version a dataclass with integer fields major, minor and patch
that sorts correctly (1.10.0 comes after 1.9.3). Add
Version.parse("1.2.3"), and make str() return "1.2.3".
Test Suites
Pending
Stdout