Object-Oriented Programming
9.1 Design and Methods · 9.2 Four Pillars · 9.3 Advanced Topics
← → or Space to navigate · F for fullscreen
total_ordering
+
The three notebooks contain the required route. Optional blocks are labeled.
Classes, instances, method binding, state, and representations
A class gives related state a clear owner and keeps validation beside its updates. Procedural functions remain useful when that organization is unnecessary.
BankAccount
str()
repr()
An invariant is a condition preserved by construction and public operations.
A class defines behavior. Each instance has its own instance attributes. self refers to the object receiving the method call.
self
type(p)
isinstance(p, Point)
p is q
p == q
class Point: def __init__(self, x, y): self.x, self.y = x, y def distance_to(self, other): return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5 p, q = Point(3, 4), Point(0, 0) print(p.distance_to(q)) # 5.0 print(isinstance(p, Point)) # True
Use the notebook's CalcTwo definition.
CalcTwo
calc = CalcTwo() print(CalcTwo.add(calc, 9, 4)) # 13: explicit receiver print(calc.add(9, 4)) # 13: Python supplies calc as self action = calc.add # store a bound method print(action(2, 3)) # 5 print(calc.last_result) # 5
calc.add is a value that remembers calc. calc.add(...) calls the method immediately.
calc.add
calc
calc.add(...)
c1.last_result
c2.last_result
c1.add(10, 5)
None
c1.subtract(10, 3)
c1.multiply(4, 6)
c2.divide(21, 3)
A return value and a state update are separate parts of a method's interface. These calculator methods do both.
__init__
@property
acct.balance
__str__
print()
__repr__
@property is not a dunder method. Our balance property has no setter. The underscore in _balance signals internal use; it is not access security.
_balance
Run the owner/balance BankAccount definition from Section 9.1 first.
acct = BankAccount('Ava', 100) returned = acct.deposit(50) print(acct.balance, returned is acct) # 150 True try: acct.withdraw(200) except ValueError as error: print(error) # Insufficient funds print(acct.balance) # 150, unchanged
deposit(50)
withdraw(200)
ValueError
deposit(-20)
Use the same Section 9.1 account class.
acct = BankAccount("O'Neil", 100) print(repr(acct)) # BankAccount("O'Neil", 100) try: acct.balance = 999 except AttributeError: print('No public balance setter')
The representation uses !r for owner and balance, preserving string quoting. Updates go through deposit() and withdraw(); both return the same account.
!r
deposit()
withdraw()
Encapsulation · Polymorphism · Inheritance · Abstraction
month_end()
checkout(payment, amount)
The independent month-end classes are separate from the numbered hierarchy. The notebook labels each teaching version before redefining its classes.
name
_name
__name
Read-only properties and validation guide normal callers. Employee exposes salary read-only; give_raise() is the one validated way to change it. Neither underscores nor a property provide confidentiality.
Employee
salary
give_raise()
The mechanics of the rewritten double-underscore spelling are optional enrichment.
Use the independent month-end classes in Section 9.2.
accounts = [CheckingAccount('Alice', 1200), InterestAccount('Bob', 5000), LoanAccount('Charlie', 2000)] for account in accounts: account.month_end() print(f'{account.owner}: {account.balance:.2f}') # Alice: 1190.00 # Bob: 5050.00 # Charlie: 2030.00
Each class implements month_end(); none needs to inherit from the others. Duck typing: the loop needs only a month_end() method, not a shared parent class. These updates return None, unlike the controlled account update methods.
Use Section 9.2's numbered-account hierarchy for this example.
savings = SavingsAccount('S-1001', 'Ava', 1200, rate=0.02) returned = savings.deposit(300) print(savings) # S-1001: Ava - $1500.00 print(returned is savings) # True print(isinstance(savings, BankAccount)) # True
super().__init__(...) reuses the parent's state setup.
super().__init__(...)
The notebook's LimitedSavingsAccount.withdraw() checks its extra rule, then returns super().withdraw(amount).
LimitedSavingsAccount.withdraw()
super().withdraw(amount)
lsa = LimitedSavingsAccount('S-9001', 'Nina', 500, min_balance=200) print(lsa.withdraw(250) is lsa) # True print(lsa.balance) # 250 try: lsa.withdraw(100) except ValueError: print('Minimum balance preserved') print(lsa.balance) # 250, unchanged
A specialization adds rules while preserving the parent's public contract.
Use PaymentMethod, CreditCard, PayPal, and checkout from the notebook.
PaymentMethod
CreditCard
PayPal
checkout
methods = [CreditCard('4242'), PayPal('student@example.com')] for method in methods: print(checkout(method, 49.99)) try: PaymentMethod() except TypeError: print('Cannot instantiate the abstract interface')
charge(amount)
The core synthesis uses both email and SMS notifiers through one caller loop.
Required: comparisons, operators, records, class variables, and factories
Use the core Point class with __eq__ and __lt__ from Section 9.3.
Point
__eq__
__lt__
points = [Point(3, 4), Point(1, 1), Point(0, 5)] print(sorted(points)) # [Point(1, 1), Point(0, 5), Point(3, 4)] print(Point(0, 5) < Point(3, 4)) # True
(distance, x, y)
Coordinates break equal-distance ties. The core example needs no decorator.
NotImplemented
False
Use the same core Point definition.
p = Point(1, 2) print(p.__eq__((1, 2)) is NotImplemented) # True print(p == (1, 2)) # False try: print(p < (1, 2)) except TypeError: print('Unsupported ordering operands')
The method declines an operand type; Python then applies dispatch and fallback. NotImplementedError is a different thing: an exception.
NotImplementedError
Use the Section 9.3 BankAccount definition with __add__.
__add__
a, b = BankAccount('Ava', 12), BankAccount('Ben', 8) merged = a + b print(a.balance, b.balance, merged.balance) # 12 8 20 print(merged is a, merged is b) # False False
deposit(amount)
a + b
a + 3
TypeError
len(obj) calls obj.__len__(); the notebook's Statement example and Ledger practice implement it.
len(obj)
obj.__len__()
Statement
from dataclasses import dataclass, field @dataclass(order=True) class Student: name: str gpa: float courses: list[str] = field(default_factory=list) students = [Student('Bob', 3.5), Student('Alice', 3.8), Student('Alice', 3.5)] print([(s.name, s.gpa) for s in sorted(students)]) # [('Alice', 3.5), ('Alice', 3.8), ('Bob', 3.5)]
The fields are compared in declaration order: name, then GPA, then courses. Type annotations do not by themselves validate input values.
Use the Student dataclass from the preceding example.
Student
s1, s2 = Student('Alice', 3.8), Student('Alice', 3.8) s1.courses.append('CS101') print(s1.courses) # ['CS101'] print(s2.courses) # [] print(s1.courses is s2.courses) # False
field(default_factory=list) calls the factory once per instance. A plain field default is appropriate for immutable values such as a string.
field(default_factory=list)
namedtuple
@dataclass
Both may have custom methods. Neither choice automatically freezes referenced lists.
from collections import namedtuple from dataclasses import dataclass Player = namedtuple('Player', ['name', 'score']) @dataclass class PlayerDC: name: str score: float print(Player('Alice', 95) == ('Alice', 95)) # True print(PlayerDC('Alice', 95) == ('Alice', 95)) # False
Use _replace() to make a modified named tuple instead of assigning a field.
_replace()
a.transfer_fee
b.transfer_fee
b.transfer_fee = 4.50
For these ordinary class defaults, reading checks the instance before the class. Instance assignment shadows the class default for that instance only. The shared mutable-list trap is optional enrichment.
@staticmethod
@classmethod
cls
Use the corresponding Section 9.3 definitions:
owner, balance = BankAccount.parse_record('Taylor:348.00') print(owner, balance) # Taylor 348.0
This snippet uses the static-method version; the next slide uses the class-method version.
Use Section 9.3's owner/balance factory class.
class BasicAccount(BankAccount): pass created = BasicAccount.from_string('Ava:100') print(type(created) is BasicAccount) # True
cls(...) constructs the calling class. It cannot invent an additional argument required by a subclass, such as tier. Preserve the factory contract or override it.
cls(...)
tier
Build @dataclass(order=True) class Payment with amount and payer.
@dataclass(order=True) class Payment
amount
payer
is_valid_amount(amount)
from_record("Ava:40.0")
cls(amount, payer)
Payment
sorted([p1, p2])
Sorted payers: ['Ben', 'Ava'] Combined: Payment(amount=65.5, payer='combined') Originals: 40.0 25.5 Invalid amount
The required route is complete. The following topics do not supply core prerequisites.
from dataclasses import dataclass @dataclass(frozen=True) class HashPoint: x: int y: int def __hash__(self): return hash((self.x, self.y)) p1, p2 = HashPoint(1, 2), HashPoint(1, 2) print(len({p1, p2})) # 1
Equal keys require equal, stable hashes. Frozen fields reject normal reassignment; referenced mutable objects remain mutable and can make hashing fail.
a > b
not (a < b) and a != b
A decorator cannot repair inconsistent equality and ordering rules. Keep per-instance lists in __init__, or use a dataclass factory.
class Name:
__init__(self, ...)
class Child(Parent):
super()
ABC
@abstractmethod
Next: Chapter 10, Functional Programming