Advanced Python

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

Take the level exam
  1. 1Objects that compare and print well

    __eq__ and __repr__.

    The idea

    Ticket PY-401 from finance: two Money objects for the same amount and currency should count as equal, and a Money in a log should show its value, not a memory address.

    Python calls special methods with double underscores for you. a == b calls a.__eq__(b), and printing in a list or a log uses __repr__. Write __eq__ to compare the amount and currency, giving back NotImplemented for other types, and __repr__ to give back text like Money(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
  2. 2Add objects with +

    __add__, and refusing mixed currencies.

    The idea

    Ticket PY-402 from finance: total = price + shipping should work for Money, and adding dollars to euros must stop with an error, not give a wrong number.

    a + b calls a.__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
  3. 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 Product refuse it, and give a margin that is always up to date and can't be set by hand.

    @property turns a method into something you read like a field: product.margin. A @price.setter runs every time someone writes product.price = ..., so it can check the value and raise ValueError. Store the real value in self._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
  4. 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. Build Order objects from those lines in one call.

    A @classmethod gets 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 back cls(...). 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
  5. 5Less boilerplate: dataclasses

    @dataclass and field(default_factory=...).

    The idea

    Ticket PY-405 from the support team: the Ticket class has grown a long __init__, __repr__ and __eq__, all written by hand. Replace them.

    @dataclass writes __init__, __repr__ and __eq__ for you from the fields you list with types. A list default must be field(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
  6. 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, shipped and shiped. Use a fixed set of choices.

    class Status(Enum) lists the only allowed values: SHIPPED = "shipped". Status("shipped") gives Status.SHIPPED, and a typo like Status("shiped") raises ValueError at 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
  7. 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 Inventory object for a shelf. Add and remove units, refuse to remove more than there is, and let len(shelf) and "Toner" in shelf work. Plan it: what does the object store, and which special methods does it need?

    In the code box, write a class Inventory with add(name, qty), remove(name, qty) that raises ValueError when there are fewer than qty units, 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) > 0

    What 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