Chapter 9

Object-Oriented Programming

9.1 Design and Methods · 9.2 Four Pillars · 9.3 Advanced Topics

← → or Space to navigate · F for fullscreen

Required Route and Optional Enrichment

Required core Optional enrichment
Classes, instances, bound methods Detailed name mangling
Initialization, properties, representations Derived ordering with total_ordering
Four pillars and public interfaces Hashability and frozen value records
Equality, ordering, and + Shared mutable class-state trap
Dataclasses, named tuples, class variables, factories No required example depends on these blocks

The three notebooks contain the required route. Optional blocks are labeled.

9.1 Design and Methods

Classes, instances, method binding, state, and representations

Why Put State and Behavior Together?

A class gives related state a clear owner and keeps validation beside its updates.
Procedural functions remain useful when that organization is unnecessary.

Decision BankAccount contract
State Owner and balance
Initial condition Nonnegative balance
Updates Positive deposits and withdrawals within available funds
Invalid operation Raise before changing state
Observation Read-only public balance, str(), and repr()

An invariant is a condition preserved by construction and public operations.

Classes and Instances

A class defines behavior. Each instance has its own instance attributes.
self refers to the object receiving the method call.

Expression Question
type(p) What is this object's class?
isinstance(p, Point) Does it belong to this class or a subclass?
p is q Are these references to the same object?
p == q What equality rule does this type provide?
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

Methods Bind a Receiver

Use the notebook's CalcTwo definition.

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.

Trace Independent Object State

After call Returned value c1.last_result c2.last_result
c1.add(10, 5) 15 15 None
c1.subtract(10, 3) 7 7 None
c1.multiply(4, 6) 24 24 None
c2.divide(21, 3) 7.0 24 7.0

A return value and a state update are separate parts of a method's interface.
These calculator methods do both.

Initialization, Properties, and Representations

Feature Role
__init__ Initialize an already created instance; return None
@property Read through attribute syntax, such as acct.balance
__str__ Human-readable text for str() and print()
__repr__ Diagnostic, ideally reconstructable text for 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.

Validate Before Mutating

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
Operation Before After Result
deposit(50) 100 150 Same account
withdraw(200) 150 150 ValueError
deposit(-20) 150 150 ValueError

Read-Only Access and Quoted Names

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.

9.2 The Four Pillars of OOP

Encapsulation · Polymorphism · Inheritance · Abstraction

Pillar Problem it addresses Focus Example
Encapsulation Keep updates consistent How state stays valid Validate before changing balance
Polymorphism Avoid type-specific caller branches Which behavior runs One month_end() loop
Inheritance Reuse a compatible public interface Who is related to whom Numbered savings account
Abstraction Keep callers independent of details What an object does checkout(payment, amount)

The independent month-end classes are separate from the numbered hierarchy.
The notebook labels each teaching version before redefining its classes.

Encapsulation Is Interface Design

Spelling Meaning
name Public
_name Internal by convention
__name Name-mangled to reduce accidental name collisions

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.

The mechanics of the rewritten double-underscore spelling are optional enrichment.

One Interface, Many Behaviors

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.

Inherit a Contract, Then Specialize

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
Retained behavior Child-specific behavior
Read-only public balance Store a savings rate
Positive update amounts Enforce a minimum balance
Updates return self Offer a fee-based withdrawal

super().__init__(...) reuses the parent's state setup.

Overriding Preserves the Update Result

The notebook's LimitedSavingsAccount.withdraw() checks its extra rule,
then returns 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.

Abstraction Through an ABC

Use PaymentMethod, CreditCard, PayPal, and checkout from the notebook.

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')
Shared interface Concrete behavior
charge(amount) Charge the card
charge(amount) Charge the PayPal account

The core synthesis uses both email and SMS notifiers through one caller loop.

9.3 Advanced OOP Topics

Required: comparisons, operators, records, class variables, and factories

Equality and Ordering Are Explicit Policies

Use the core Point class with __eq__ and __lt__ from Section 9.3.

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
Method Policy
__eq__ Compare coordinates
__lt__ Compare (distance, x, y)

Coordinates break equal-distance ties. The core example needs no decorator.

NotImplemented Is Not 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.

Define the Result of an Operator

Use the Section 9.3 BankAccount definition with __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
Operation Meaning
deposit(amount) Change one account and return it
a + b Return a new merged account, leaving both operands unchanged
a + 3 Neither type supports this pair; raises TypeError

len(obj) calls obj.__len__(); the notebook's Statement example and Ledger practice implement it.

Dataclass Ordering Follows Field Order

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.

Mutable Defaults Must Be Independent

Use the Student dataclass from the preceding example.

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.

Named Tuples and Dataclasses Offer Different Interfaces

Decision namedtuple Default @dataclass
Named fields Yes Yes
Indexing / unpacking Tuple behavior Not generated
Field reassignment Rejected Allowed
Representation Type and field names Type and field names
Equality Tuple-compatible values Normally the same dataclass type
Typical use Read-only, tuple-compatible record Annotated record with evolving behavior

Both may have custom methods. Neither choice automatically freezes referenced lists.

A Record Comparison You Can Predict

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.

Class Defaults and Instance Shadowing

Stage Class fee a.transfer_fee b.transfer_fee
Default 2.50 2.50 2.50
Assign class fee 3.00 3.00 3.00 3.00
Assign b.transfer_fee = 4.50 3.00 3.00 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.

Static and Class Methods Differ in Binding

Question @staticmethod @classmethod
Implicit receiver None Calling class (cls)
Typical use Parsing helper Alternative constructor
State access Explicit arguments / named objects Class receiver / explicit arguments

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.

Factories Need Compatible Initializers

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.

Your Turn: Advanced OOP Review

Build @dataclass(order=True) class Payment with amount and payer.

Feature Requirement
@staticmethod is_valid_amount(amount) is true for positive amounts
@classmethod from_record("Ava:40.0") parses, validates, returns cls(amount, payer)
__add__ New Payment with the summed amount; NotImplemented otherwise
Ordering sorted([p1, p2]) follows field order: amount first
Sorted payers: ['Ben', 'Ava']
Combined: Payment(amount=65.5, payer='combined')
Originals: 40.0 25.5
Invalid amount

Optional Enrichment

The required route is complete. The following topics do not supply core prerequisites.

Optional: Frozen Values and Stable Hashes

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.

Optional: Derived Ordering and Shared Mutable State

Extension Connection to the required route
total_ordering Supply __eq__ and __lt__; a > b is computed as not (a < b) and a != b
Frozen value-record practice Keep attributes used for equality and hashing stable
Shared mutable class variables Mutating a shared list differs from assigning an instance attribute

A decorator cannot repair inconsistent equality and ordering rules.
Keep per-instance lists in __init__, or use a dataclass factory.

Chapter 9 Quick Reference

Required concept Key syntax / decision
Class and initializer class Name:; __init__(self, ...) initializes state
Public read-only property @property; update through validated methods
Inheritance class Child(Parent):; reuse setup with super()
Abstract interface ABC, @abstractmethod, concrete implementations
Comparison __eq__, __lt__, and NotImplemented
Record choices Field order, mutable defaults, tuple compatibility
Class variables Shared default versus instance shadowing
Factories cls(...) requires a compatible initializer

End of Chapter 9

Next: Chapter 10, Functional Programming