dataclasses: classes that print and compare
A Ticket from lesson 19 prints as a memory address, and two tickets with the same data are not equal. A dataclass fixes both and writes __init__ for you.
from dataclasses import dataclass
@dataclass
class Ticket:
id: int
customer: str
text: str
category: str = "unsorted"
ticket = Ticket(1, "Asha", "I was charged twice for one order")
print(ticket)
print(ticket == Ticket(1, "Asha", "I was charged twice for one order"))@dataclass is a decorator: a line starting with @ that changes the function or class right below it. This one reads the fields listed in the class and writes the __init__ that stores them, a readable printout and an equality check.
id: int names a field and the type it should hold. That annotation is a type hint, and lesson 23 is about them. category: str = "unsorted" gives a default, so it can be left out of the call.
Methods still work
@dataclass
class Ticket:
id: int
customer: str
text: str
category: str = "unsorted"
def categorise(self):
text = self.text.lower()
self.category = "billing" if "refund" in text else "other"
ticket = Ticket(3, "Chen", "Can I get a refund for the blue mug?")
ticket.categorise()
print(ticket)"billing" if ... else "other" is an if and else squeezed into one value: the first when the condition is true, the second when not.
A hint is not a check
ticket = Ticket("one", "Asha", 42)
print(ticket)A dataclass stores "one" and 42 without complaint, even though the hints say int and str. The hints describe; nothing enforces them. Lesson 24 uses a class that does check.
- Add a field
priority: int = 3and print a ticket. - Put a field without a default below one with a default, and read the error.
- Compare two tickets that differ only in
category.
Little by little, you're building something great.