Level recap · Advanced Python · Level 4
Object design
Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.
What this level teaches: Classes that compare, add, guard their values and stay short with dataclasses and enums.
7 classesLevel exam
1Objects that compare and print well
__eq__ and __repr__.
The idea
Ticket PY-401 from finance: two
Moneyobjects for the same amount and currency should count as equal, and aMoneyin a log should show its value, not a memory address.Python calls special methods with double underscores for you.
a == bcallsa.__eq__(b), and printing in a list or a log uses__repr__. Write__eq__to compare the amount and currency, giving backNotImplementedfor other types, and__repr__to give back text likeMoney(12.5, 'USD').The code
class Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency def __eq__(self, other): if not isinstance(other, Money): return NotImplemented return (self.amount, self.currency) == (other.amount, other.currency) def __repr__(self): return f"Money({self.amount!r}, {self.currency!r})" print(Money(12.5, "USD") == Money(12.5, "USD"), Money(3, "EUR"))What it shows
PASS Right on new test values
2Add objects with +
__add__, and refusing mixed currencies.
The idea
Ticket PY-402 from finance:
total = price + shippingshould work for Money, and adding dollars to euros must stop with an error, not give a wrong number.a + bcallsa.__add__(b). Give back a new Money with the amounts added, rounded to cents. When the currencies differ,raise ValueError(...), so the mistake shows at once instead of turning into a wrong invoice.The code
class Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency def __add__(self, other): if self.currency != other.currency: raise ValueError("Different currencies") return Money(round(self.amount + other.amount, 2), self.currency) total = Money(10.25, "USD") + Money(4.5, "USD") print(total.amount, total.currency)What it shows
PASS Right on new test values
3Guard a value with a property
@property and a setter.
The idea
Ticket PY-403 from the catalog team: a negative price slipped into the shop last week. Make
Productrefuse it, and give amarginthat is always up to date and can't be set by hand.@propertyturns a method into something you read like a field:product.margin. A@price.setterruns every time someone writesproduct.price = ..., so it can check the value andraise ValueError. Store the real value inself._price. A property with no setter can't be written to at all.The code
class Product: def __init__(self, name, price, cost): self.name = name self.cost = cost self.price = price @property def price(self): return self._price @price.setter def price(self, value): if value < 0: raise ValueError("Price can't be negative") self._price = value @property def margin(self): return round(self.price - self.cost, 2) shelf = Product("Shelf", 75, 40) print(shelf.margin)What it shows
PASS Right on new test values
4Another way to build an object
@classmethod as a factory.
The idea
Ticket PY-404 from the integrations team: orders arrive from the old system as text like
17;Cedar Law;250.50. BuildOrderobjects from those lines in one call.A
@classmethodgets the class itself as its first argument,cls, instead of an object. That makes it a good second way to build objects:Order.from_line(text)splits the text, converts the parts and gives backcls(...). It keeps the parsing next to the class it belongs to.The code
class Order: def __init__(self, id, customer, total): self.id = id self.customer = customer self.total = total @classmethod def from_line(cls, line): order_id, customer, total = line.split(";") return cls(int(order_id), customer, float(total)) order = Order.from_line("17;Cedar Law;250.50") print(order.id, order.customer, order.total)What it shows
PASS Right on new test values
5Less boilerplate: dataclasses
@dataclass and field(default_factory=...).
The idea
Ticket PY-405 from the support team: the
Ticketclass has grown a long__init__,__repr__and__eq__, all written by hand. Replace them.@dataclasswrites__init__,__repr__and__eq__for you from the fields you list with types. A list default must befield(default_factory=list): a plain= []would share one list between every ticket, so a tag added to one would show up on all of them.The code
from dataclasses import dataclass, field @dataclass class Ticket: priority: int title: str tags: list = field(default_factory=list) print(Ticket(2, "Refund"))What it shows
PASS Right on new test values
6Fixed choices: Enum
enum.Enum.
The idea
Ticket PY-406 from the data team: order statuses are typed by hand as text, and the reports found
Shipped,shippedandshiped. Use a fixed set of choices.class Status(Enum)lists the only allowed values:SHIPPED = "shipped".Status("shipped")givesStatus.SHIPPED, and a typo likeStatus("shiped")raisesValueErrorat once. Members work as dict keys, so a count by status is safe.The code
from enum import Enum class Status(Enum): SHIPPED = "shipped" RETURNED = "returned" PENDING = "pending" def count_by_status(values): counts = {} for value in values: status = Status(value) counts[status] = counts.get(status, 0) + 1 return counts print(Status("returned"), len(count_by_status(["shipped", "pending", "shipped"])))What it shows
PASS Right on new test values
7On your own: an inventory class
A class that works with len and in, with no gold line.
The idea
Ticket PY-407 from the warehouse lead: one
Inventoryobject for a shelf. Add and remove units, refuse to remove more than there is, and letlen(shelf)and"Toner" in shelfwork. Plan it: what does the object store, and which special methods does it need?In the code box, write a class
Inventorywithadd(name, qty),remove(name, qty)that raisesValueErrorwhen there are fewer thanqtyunits,units(name)that gives the units (0 if none),__len__(how many products have more than 0 units) and__contains__(true when a product has more than 0 units). Then press Run my code.The code
class Inventory: def __init__(self): self.stock = {} def add(self, name, qty): self.stock[name] = self.stock.get(name, 0) + qty def remove(self, name, qty): if self.units(name) < qty: raise ValueError(f"Only {self.units(name)} {name} left") self.stock[name] -= qty def units(self, name): return self.stock.get(name, 0) def __len__(self): return sum(1 for units in self.stock.values() if units > 0) def __contains__(self, name): return self.units(name) > 0What it shows
PASS Right on new test values
Ready for the exam? The level exam is one real task that uses what this recap covers.
Take the level exam