Python · Level 3 OOP

Dataclasses

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

@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

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".

solution.py
Test Suites Pending
Stdout