9.3. Advanced OOP Topics#

Hide code cell source

import sys
from pathlib import Path

current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent
        break
else:
    project_root = Path.cwd().parent.parent

sys.path.insert(0, str(project_root))

from shared import thinkpython, diagram, jupyturtle, download

sys.modules['thinkpython'] = thinkpython
sys.modules['diagram'] = diagram
sys.modules['jupyturtle'] = jupyturtle
sys.modules['download'] = download

This section covers six topics. Its banking examples reuse the owner/balance BankAccount from OOP Design and Methods, not the numbered-account hierarchy from The Four Pillars.

Required topic

What it adds

Comparison methods

Value equality and ordering with __eq__ and __lt__

Operator overloading

A nonmutating + operation with a defined result

@dataclass

Generated methods, field order, and independent mutable defaults

namedtuple

Tuple-compatible records with named fields

Class vs. instance variables

Shared defaults and per-instance shadowing

Static and class methods

Parsing helpers and alternative constructors

Optional enrichment: total_ordering, hashability, frozen dataclasses, and the shared mutable class-variable trap are labeled where they appear. The required examples and practice do not depend on them.

9.3.1. Comparison Dunder Methods#

For a new class that inherits object’s equality behavior, two distinct instances compare unequal even if their attributes agree. is tests identity. Defining __eq__ lets == express the class’s chosen value-equality rule.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Point({self.x}, {self.y})'

p1 = Point(1, 2)
p2 = Point(1, 2)

print(p1 == p2)   # False: identity check by default
print(p1 is p2)   # False
False
False

Adding __eq__ makes == compare by value instead.

A binary special method receives the other operand as other. Before reading its attributes, decide whether that operand’s type is supported. Return the special value NotImplemented when it is not. This means “this method does not handle that type,” not “the values are unequal.” It is also different from raising NotImplementedError.

Python can then try the other operand’s comparison method or an operator-specific fallback. For two unsupported equality operands, == ultimately falls back to identity. Unsupported ordering or addition normally raises TypeError when neither operand handles the operation. Never treat NotImplemented itself as a Boolean answer.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Point({self.x}, {self.y})'

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return self.x == other.x and self.y == other.y

p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(3, 4)

print(p1 == p2)   # now True
print(p1 is p2)   # still False
print(p1 == p3)   # False

# print(p1)
True
False
False

Predict the difference between asking the method directly and using the equality operator:

print(p1.__eq__((1, 2)) is NotImplemented)  # True: this method declines the tuple
print(p1 == (1, 2))                        # False: Python applies equality fallback
try:
    print(p1 < (1, 2))
except TypeError:
    print('Ordering is not supported for this pair')
True
False
Ordering is not supported for this pair

The direct method call returns a sentinel, while == returns a Boolean after dispatch and fallback. The ordering attempt raises because this version of Point has no ordering implementation. The next example adds an ordering rule for pairs of points.

9.3.1.1. Ordering with __lt__#

To support sorted(), min(), and max(), define __lt__(self, other). Return a Boolean for supported operands and NotImplemented otherwise. Equality and ordering are design decisions: this version compares points by distance from the origin, breaking equal-distance ties by coordinates.

The tuple (distance, x, y) is the comparison key. Python compares its first differing element, so equal-distance points still have a deterministic order consistent with coordinate equality. The core example needs no decorator. Deriving additional comparison operators with total_ordering is optional enrichment below.

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f'Point({self.x}, {self.y})'

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __lt__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        own_key = (math.hypot(self.x, self.y), self.x, self.y)
        other_key = (math.hypot(other.x, other.y), other.x, other.y)
        return own_key < other_key

points = [Point(3, 4), Point(1, 1), Point(0, 2), Point(0, 5)]
print(sorted(points))
print(min(points))
print(max(points))
print(Point(0, 5) < Point(3, 4))  # True: same distance, compare x next
[Point(1, 1), Point(0, 2), Point(0, 5), Point(3, 4)]
Point(1, 1)
Point(3, 4)
True

Point(0, 5) and Point(3, 4) are both five units from the origin. The first coordinate breaks the tie, so the first point sorts earlier. If you only need a one-off sort, sorted(points, key=...) from Tuples can supply an ordering without changing the class; implement __lt__ when that order belongs to the type’s interface.

### Exercise: Comparison Dunders
# Required core.
# 1. Define Transaction with account and amount, plus __repr__ using !r for account.
# 2. Define __eq__ using both attributes and __lt__ using (amount, account).
#    Return NotImplemented for an unsupported operand type.
# 3. Create Transaction('A-1', 50), Transaction('A-2', 20), and Transaction('A-1', 50).
# 4. Print equality of the first and third, sorted transactions, and the maximum.
# No decorator or __hash__ is required. The optional value-object extension is below.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class Transaction:
    def __init__(self, account, amount):
        self.account = account
        self.amount = amount

    def __repr__(self):
        return f'Transaction({self.account!r}, {self.amount})'

    def __eq__(self, other):
        if not isinstance(other, Transaction):
            return NotImplemented
        return (self.account, self.amount) == (other.account, other.amount)

    def __lt__(self, other):
        if not isinstance(other, Transaction):
            return NotImplemented
        return (self.amount, self.account) < (other.amount, other.account)

t1 = Transaction('A-1', 50)
t2 = Transaction('A-2', 20)
t3 = Transaction('A-1', 50)
print(t1 == t3)
print(sorted([t1, t2, t3]))
print(max([t1, t2, t3]))
True
[Transaction('A-2', 20), Transaction('A-1', 50), Transaction('A-1', 50)]
Transaction('A-1', 50)

9.3.2. Operator Overloading#

By defining special methods, you can control how Python operators behave on your own types. Most operators, and some built-in functions such as len(), have a corresponding dunder method:

Operator

Method

Example

+

__add__

a + b

==

__eq__

a == b

<

__lt__

a < b

len()

__len__

len(a)

This section focuses on + and len(); the comparison methods __eq__ and __lt__ are covered above.

Here is __add__ defined on BankAccount. When two accounts are added together, a new merged account is returned:

class BankAccount:
    """A teaching account with controlled balance updates."""

    def __init__(self, owner="Unknown", balance=0.0):
        if balance < 0:
            raise ValueError('Starting balance cannot be negative')
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        """Current balance, read-only through the public interface."""
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError('Deposit must be positive')
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError('Withdrawal must be positive')
        if amount > self._balance:
            raise ValueError('Insufficient funds')
        self._balance -= amount
        return self

    def __str__(self):
        return f"BankAccount(owner={self.owner}, balance=${self._balance:.2f})"

    def __repr__(self):
        return f"BankAccount({self.owner!r}, {self._balance!r})"

    def __add__(self, other):
        """Return a new merged account; leave both operands unchanged."""
        if not isinstance(other, BankAccount):
            return NotImplemented
        return BankAccount(f'{self.owner}&{other.owner}', self.balance + other.balance)
a = BankAccount("Ava", 12.00)
b = BankAccount("Ben", 8.00)
print(a + b)   # BankAccount(owner=Ava&Ben, balance=$20.00)
BankAccount(owner=Ava&Ben, balance=$20.00)

The operation returns a new object; neither account is mutated. The result’s owner and balance follow the merge policy stated by this example. Compare that with deposit(), which changes one existing object and returns it. Predict the final balances and the unsupported-operand outcome:

merged = a + b
print(a.balance, b.balance, merged.balance)  # 12.0 8.0 20.0
print(merged is a, merged is b)             # False False
try:
    print(a + 3)
except TypeError:
    print('Cannot merge an account with an integer')
12.0 8.0 20.0
False False
Cannot merge an account with an integer

When Python evaluates a + b, it calls a.__add__(b) automatically. Changing the behavior of an operator so that it works with programmer-defined types is called operator overloading.

Built-in functions use special methods too. len(obj) calls obj.__len__(), which must return a nonnegative integer. A statement that holds a list of amounts can report how many it has:

class Statement:
    def __init__(self, owner, amounts):
        self.owner = owner
        self.amounts = amounts

    def __len__(self):
        return len(self.amounts)

statement = Statement('Ava', [100, -20, 35])
print(len(statement))   # 3
3
### Exercise: Operator Overloading
#   1. Define a class Ledger whose __init__(self, owner, entries) stores
#      the owner and a list of amounts.
#   2. Define __add__ so that ledger1 + ledger2 returns a new Ledger whose
#      owner is 'owner1&owner2' and whose entries combine both lists.
#      Return NotImplemented if the other object is not a Ledger.
#   3. Define __len__ to return the number of entries.
#   4. Create Ledger('Ava', [100, -20]) and Ledger('Ben', [50]), add them,
#      and print the combined owner, entries, and len().
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class Ledger:
    def __init__(self, owner, entries):
        self.owner = owner
        self.entries = entries

    def __add__(self, other):
        if not isinstance(other, Ledger):
            return NotImplemented
        return Ledger(f'{self.owner}&{other.owner}', self.entries + other.entries)

    def __len__(self):
        return len(self.entries)

a = Ledger('Ava', [100, -20])
b = Ledger('Ben', [50])
combined = a + b

print(combined.owner)
print(combined.entries)
print(len(combined))
Ava&Ben
[100, -20, 50]
3

9.3.3. @dataclass#

@dataclass is a decorator from the standard library that auto-generates common dunder methods (__init__, __repr__, __eq__) for a class based on its annotated fields, eliminating boilerplate.

Dataclasses give type annotations a second job. In a regular class, name: str is mostly a hint for readers and tools. In a dataclass, an annotated class variable also becomes a field that @dataclass uses to generate __init__, __repr__, and comparison behavior.

The table lists its most useful options.

Option

Effect

eq=True (default)

Auto-generates __eq__ based on fields

order=True

Also generates __lt__, __le__, __gt__, __ge__

frozen=True (optional below)

Rejects normal field reassignment; hashing still requires hashable field values

field(default_factory=...)

Safe default for mutable fields like lists

When order=True is set, fields are compared in declaration order (here name first, then gpa), so sorted([s1, s2]) places Alice before Bob because 'Alice' < 'Bob' alphabetically.

from dataclasses import dataclass, field

@dataclass(order=True)
class Student:
    name: str
    gpa: float
    courses: list[str] = field(default_factory=list)   # safe mutable default

s1 = Student('Alice', 3.8)
s2 = Student('Bob', 3.5)
s3 = Student('Alice', 3.8)

print(s1 == s3)          # True: same field values
print(sorted([s1, s2]))  # sorted lexicographically by (name, gpa)
s1.courses.append('CS101')
print(s1)
True
[Student(name='Alice', gpa=3.8, courses=[]), Student(name='Bob', gpa=3.5, courses=[])]
Student(name='Alice', gpa=3.8, courses=['CS101'])

Field order controls comparisons; it does not mean GPA is the primary key. Predict which Alice comes first, then inspect each instance’s courses list. default_factory=list calls list() separately for each instance; it does not share one default list. Type annotations document expected types but do not themselves validate constructor inputs.

s4 = Student('Alice', 3.5)
print([(student.name, student.gpa) for student in sorted([s2, s1, s4])])
print(s1.courses)  # ['CS101']
print(s3.courses)  # [], unchanged when s1.courses was updated
print(s1.courses is s3.courses)  # False
[('Alice', 3.5), ('Alice', 3.8), ('Bob', 3.5)]
['CS101']
[]
False

A field can also have a plain default value. Write the value after the annotation, as in category: str = 'general', and callers may then leave that argument out. Fields with defaults must come after the fields without defaults. Plain defaults are for immutable values such as strings, numbers, and None. A mutable default such as a list still needs field(default_factory=list), so that each instance gets its own new list; @dataclass rejects notes: list = [] with a ValueError.

from dataclasses import dataclass

@dataclass
class Task:
    title: str
    category: str = 'general'   # plain default for an immutable value
    priority: int = 1

print(Task('Write report'))              # both defaults used
print(Task('Fix bug', 'code', 3))        # defaults overridden
Task(title='Write report', category='general', priority=1)
Task(title='Fix bug', category='code', priority=3)
### Exercise: Dataclasses
# Required core.
# 1. Define @dataclass(order=True) Expense with amount: float, category: str,
#    and notes: list[str] using field(default_factory=list).
# 2. Print three expenses sorted by amount, then category for equal amounts.
# 3. Append a note to one expense; print another expense's notes to confirm independence.
# The frozen Currency variation follows as optional enrichment.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from dataclasses import dataclass, field

@dataclass(order=True)
class Expense:
    amount: float
    category: str
    notes: list[str] = field(default_factory=list)

e1 = Expense(42.50, 'groceries')
e2 = Expense(12.00, 'transit')
e3 = Expense(99.99, 'utilities')
print(sorted([e1, e2, e3]))

e1.notes.append('weekly shop')
print(e1)
print(e2.notes)  # [], independent of e1.notes
[Expense(amount=12.0, category='transit', notes=[]), Expense(amount=42.5, category='groceries', notes=[]), Expense(amount=99.99, category='utilities', notes=[])]
Expense(amount=42.5, category='groceries', notes=['weekly shop'])
[]

9.3.3.1. Frozen Dataclasses#

Optional enrichment. Skip this subsection and the hashability/comparison extension that follows it for the required route; continue at namedtuple.

frozen=True rejects normal field assignment and deletion. It does not freeze objects referenced by fields: a list field can still be mutated. With the default equality behavior, Python generates a hash method, but calling it still requires the participating field values to be hashable. The integer-valued Color below satisfies that requirement.

from dataclasses import dataclass

@dataclass(frozen=True)
class Color:
    r: int
    g: int
    b: int

red = Color(255, 0, 0)
print(red)
print(hash(red))   # hashable

palette = {red, Color(0, 255, 0), Color(0, 0, 255)}
print(palette)

try:
    red.r = 128    # raises FrozenInstanceError
except Exception as e:
    print(type(e).__name__, e)
Color(r=255, g=0, b=0)
4091835460043580556
{Color(r=0, g=255, b=0), Color(r=255, g=0, b=0), Color(r=0, g=0, b=255)}
FrozenInstanceError cannot assign to field 'r'
### Exercise: Optional Frozen Records
# Optional enrichment.
# Define frozen Currency with code and symbol, put duplicate values in a set,
# and catch a field reassignment error.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from dataclasses import dataclass

@dataclass(frozen=True)
class Currency:
    code: str
    symbol: str

usd = Currency('USD', '$')
cad = Currency('CAD', 'C$')
print({usd, cad, Currency('USD', '$')})   # the duplicate USD appears once

try:
    usd.symbol = 'US$'
except Exception as e:
    print(type(e).__name__)
{Currency(code='USD', symbol='$'), Currency(code='CAD', symbol='C$')}
FrozenInstanceError

9.3.3.2. Hashability and __hash__#

Optional enrichment. Read after Frozen Dataclasses; the required comparison lesson does not require hashing.

Defining value equality on an ordinary class without supplying a hash makes its instances unhashable. That is appropriate for the mutable core Point. A dictionary or set requires stable hashes: equal objects must have equal hashes, and the attributes used for equality and hashing must not change while an object is stored.

The optional HashPoint below is a frozen dataclass. Its explicit __hash__ shows the tuple-hashing rule; in this particular frozen dataclass Python could generate that method automatically. It uses a separate name so the core Point definition remains unchanged.

from dataclasses import dataclass

@dataclass(frozen=True)
class HashPoint:
    x: int
    y: int

    def __hash__(self):
        return hash((self.x, self.y))

p1 = HashPoint(1, 2)
p2 = HashPoint(1, 2)
p3 = HashPoint(3, 4)
point_set = {p1, p2, p3}
print(len(point_set))     # 2: equal objects collapse
lookup = {p1: 'origin-ish', p3: 'far'}
print(lookup[p2])         # origin-ish
2
origin-ish

Optional enrichment: deriving comparisons.

The @functools.total_ordering decorator derives the missing ordering methods from two definitions you supply:

  1. __eq__: define or inherit equality appropriate to the value policy; the decorator never derives it.

  2. Any one of __lt__, __le__, __gt__, or __ge__: the decorator fills in the remaining three.

You define

Decorator derives

__eq__

Not generated; define or inherit the intended equality rule

one of __lt__ / __le__ / __gt__ / __ge__

the other three ordering methods

Using __lt__ is conventional: < reads naturally as “is a less than b?”, which maps cleanly onto sort order, but any of the four works.

For example, if you define __lt__ and __eq__, the decorator computes the other three from them:

Expression

Computed as

a <= b

a < b or a == b

a > b

not (a < b) and a != b

a >= b

not (a < b)

Every derived method calls a.__lt__(b) with a on the left, so it never needs the other object to define <.

Performance note: because the derived methods add an extra function call layer, @total_ordering is marginally slower than writing all six methods explicitly. Consider hand-writing comparisons only if profiling identifies the generated methods as a bottleneck.

Use equality and ordering rules that agree on ties. Comparing by (amount, account) makes two different accounts with the same amount distinguishable in both equality and ordering. A decorator cannot repair an inconsistent comparison policy.

### Exercise: Optional Comparison Extension
# Optional enrichment; no later core example depends on this cell.
# Define a frozen dataclass ValueTransaction with account: str and amount: float.
# Use @total_ordering with explicit __eq__ and __lt__ (key: (amount, account)).
# Define __hash__ from (account, amount).
# Print equality, sorted values, max, and the size of a set with one duplicate.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from dataclasses import dataclass
from functools import total_ordering

@total_ordering
@dataclass(frozen=True)
class ValueTransaction:
    account: str
    amount: float

    def __eq__(self, other):
        if not isinstance(other, ValueTransaction):
            return NotImplemented
        return (self.account, self.amount) == (other.account, other.amount)

    def __lt__(self, other):
        if not isinstance(other, ValueTransaction):
            return NotImplemented
        return (self.amount, self.account) < (other.amount, other.account)

    def __hash__(self):
        return hash((self.account, self.amount))

v1 = ValueTransaction('A-1', 50)
v2 = ValueTransaction('A-2', 20)
v3 = ValueTransaction('A-1', 50)
print(v1 == v3)
print(sorted([v1, v2, v3]))
print(max([v1, v2, v3]))
print(len({v1, v2, v3}))
True
[ValueTransaction(account='A-2', amount=20), ValueTransaction(account='A-1', amount=50), ValueTransaction(account='A-1', amount=50)]
ValueTransaction(account='A-1', amount=50)
2

9.3.4. namedtuple#

namedtuple from collections creates a lightweight, immutable data class in one line. It gives you named fields (like a regular class) plus the efficiency and unpacking of a plain tuple. Use it for simple, read-only data containers that don’t need methods.

A named tuple is a tuple subclass: positional access and unpacking are part of its interface. A dataclass is a regular class with generated methods. Neither is a universal replacement for the other.

Decision

namedtuple

Default @dataclass

Named field access

Yes

Yes

Positional indexing / unpacking

Tuple behavior

Not generated

Reassign a field

Rejected

Allowed

Generated representation

Includes type and named fields

Includes type and named fields

Equality

Tuple values; can equal an ordinary tuple

Normally requires the same dataclass type

Typical fit

Tuple-compatible read-only record

Record with annotations and evolving behavior

Both can hold mutable objects in their fields; tuple immutability prevents replacing a field, not mutating a referenced list. Both can have custom methods, although simple named tuples often need none.

from collections import namedtuple

# namedtuple('ClassName', ['field1', 'field2', ...]) returns a new class
Point = namedtuple('Point', ['x', 'y'])

p = Point(3, 4)
print(p)              # Point(x=3, y=4)
print(p == Point(3, 4))   # True: value equality built in
Point(x=3, y=4)
True
from collections import namedtuple

# Access by attribute name, by index, or by tuple unpacking: all work
p = Point(3, 4)
print(p.x, p.y)     # by name
print(p[0], p[1])   # by index

x, y = p            # tuple unpacking
print(x, y)
3 4
3 4
3 4
# namedtuple instances are immutable: fields cannot be changed after creation
try:
    p.x = 10
except AttributeError as e:
    print(e)

# But you can create a modified copy with _replace()
p2 = p._replace(x=10)
print(p2)   # Point(x=10, y=4)
can't set attribute
Point(x=10, y=4)
# namedtuple vs @dataclass: when to use which
from dataclasses import dataclass

# namedtuple: one line, immutable, no boilerplate: good for simple data records
Player = namedtuple('Player', ['name', 'score'])
p1 = Player('Alice', 95)
print(p1)   # Player(name='Alice', score=95)

# @dataclass: mutable by default, supports methods, type annotations
@dataclass
class PlayerDC:
    name: str
    score: float

p2 = PlayerDC('Alice', 95)
p2.score = 100   # mutation allowed
print(p2)        # PlayerDC(name='Alice', score=100)
Player(name='Alice', score=95)
PlayerDC(name='Alice', score=100)

Predict these comparisons from the table, then run them. A tuple-compatible record and a dataclass do not promise the same equality behavior.

print(Player('Alice', 95) == ('Alice', 95))    # True
print(PlayerDC('Alice', 95) == ('Alice', 95))  # False
True
False
### Exercise: namedtuple
# 1. Define a namedtuple called Employee with fields: name, department, salary.
# 2. Create two Employee instances.
# 3. Access the salary of the second employee by attribute name and by index.
# 4. Try to change a field and confirm it raises an AttributeError.
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
from collections import namedtuple

Employee = namedtuple('Employee', ['name', 'department', 'salary'])

e1 = Employee('Alice', 'Engineering', 95000)
e2 = Employee('Bob', 'Marketing', 78000)

print(e1)
print(e2.salary)    # by attribute name
print(e2[2])        # by index: same field

try:
    e1.salary = 100000
except AttributeError as e:
    print(e)
Employee(name='Alice', department='Engineering', salary=95000)
78000
78000
can't set attribute

9.3.5. Class vs. Instance Variables#

A class variable is defined directly in the class body, outside any method. It is shared across all instances. An instance variable is set on self inside a method and belongs only to that one object.

Confusing the two is one of the most common OOP bugs in Python.

class Dog:
    species = 'Canis lupus familiaris'   # class variable: shared by all dogs

    def __init__(self, name):
        self.name = name                  # instance variable: unique per dog

d1 = Dog('Rex')
d2 = Dog('Fido')

print(d1.species)    # 'Canis lupus familiaris'
print(d2.species)    # same: shared
print(d1.name)       # 'Rex'
print(d2.name)       # 'Fido'
Canis lupus familiaris
Canis lupus familiaris
Rex
Fido

The same idea fits banking. A bank name and a default transfer fee belong to the bank, not to one customer, so AccountSettings stores them as class variables. Updating a class variable through the class changes the value every instance sees. For these ordinary class defaults, reading first checks the instance, then its class. Assigning b.transfer_fee = 4.50 creates an instance attribute that shadows the class value for b; it does not update AccountSettings.transfer_fee. Later class updates are visible only to instances that have not shadowed that name.

class AccountSettings:
    bank_name = 'Phelps County Bank'   # shared by all instances
    transfer_fee = 2.50               # shared default fee

    def __init__(self, owner):
        self.owner = owner

a = AccountSettings('Ava')
b = AccountSettings('Ben')

print(a.bank_name, '|', b.bank_name)
print(f'Initial fee -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}')

# Update class variable: both instances see the new shared value
AccountSettings.transfer_fee = 3.00
print(f'After class update -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}')

# Assign via one instance: creates an instance attribute (shadows class variable for that object only)
b.transfer_fee = 4.50
print(f'After instance assignment -> a: ${a.transfer_fee:.2f}, b: ${b.transfer_fee:.2f}, class: ${AccountSettings.transfer_fee:.2f}')
Phelps County Bank
 | Phelps County Bank
Initial fee -> a: $2.50, b: $2.50
After class update -> a: $3.00, b: $3.00
After instance assignment -> a: $3.00, b: $4.50, class: $3.00

Stage

Class fee

a.transfer_fee

b.transfer_fee

Initial class default

2.50

2.50

2.50

Assign AccountSettings.transfer_fee = 3.00

3.00

3.00

3.00

Assign b.transfer_fee = 4.50

3.00

3.00

4.50

A list created as self.history = [] in __init__ belongs to that instance, as in the earlier TaskList and dataclass examples. The following shared-list counterexample is optional; the required exercise uses independent instance lists.

### Exercise: Class vs. Instance Variables
#   1. Define a class SavingsAccount with a class variable interest_rate = 0.02
#      and instance variables owner, balance, and history (a new empty list
#      created in __init__).
#   2. Create a1 = SavingsAccount('Ava', 1000) and a2 = SavingsAccount('Ben', 500).
#   3. Set SavingsAccount.interest_rate = 0.03 and print both accounts' rates.
#   4. Assign a1.interest_rate = 0.05, then print a1's rate, a2's rate,
#      and SavingsAccount.interest_rate.
#   5. Append 'opened' to a1.history and print both history lists.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class SavingsAccount:
    interest_rate = 0.02              # class variable: shared default

    def __init__(self, owner, balance):
        self.owner = owner            # instance variables
        self.balance = balance
        self.history = []             # a new list for each account

a1 = SavingsAccount('Ava', 1000)
a2 = SavingsAccount('Ben', 500)

SavingsAccount.interest_rate = 0.03
print(a1.interest_rate, a2.interest_rate)

a1.interest_rate = 0.05               # shadows the class variable on a1 only
print(a1.interest_rate, a2.interest_rate, SavingsAccount.interest_rate)

a1.history.append('opened')
print(a1.history, a2.history)
0.03 0.03
0.05 0.03 0.03
['opened'] []

9.3.5.1. The Mutation Trap#

Optional enrichment. No required example depends on running this shared-list counterexample.

Assigning to a class variable via an instance creates a new instance variable that shadows the class variable; it does not change the class variable for all instances.

But mutating a mutable class variable (like a list) does affect all instances, because no new variable is created.

class Counter:
    count = 0            # class variable
    history = []         # mutable class variable: danger zone

    def __init__(self, name):
        self.name = name

a = Counter('a')
b = Counter('b')

# Reassignment via instance: creates a new instance variable on `a` only
a.count = 99
print(a.count)           # 99: instance variable on a
print(b.count)           # 0 : class variable unchanged
print(Counter.count)     # 0

# Mutation via instance: modifies the shared class-level list
a.history.append('event')
print(b.history)         # ['event']: b sees the change!
print(Counter.history)   # ['event']
99
0
0
['event']
['event']

Rule of thumb:

  • Use class variables for constants or data that truly belongs to the class (e.g., species, MAX_SIZE).

  • Use instance variables (set in __init__) for data that belongs to individual objects.

  • Never use a mutable class variable as a default container. Use field(default_factory=list) with @dataclass, or set the list in __init__.

9.3.6. Static and Class Methods#

Not every method needs an instance. Python provides two decorators for methods that are attached to the class itself rather than an instance:

Decorator

First parameter

Typical use

@staticmethod

(none)

Utility function logically grouped with the class

@classmethod

cls (the class itself)

Alternative constructors / factory methods

Both decorators come up naturally alongside class variables, because all three belong to the class rather than any one instance.

9.3.6.1. Static Methods#

A static method is a regular function that lives inside a class for organizational reasons. It receives neither self nor cls, so it receives no implicit object or class. It can still use an object or class supplied explicitly as an argument; the decorator does not prohibit such access.

A common use-case is a validation or parsing helper that supports other methods without depending on object state:

class BankAccount:
    """A teaching account with controlled balance updates."""

    def __init__(self, owner="Unknown", balance=0.0):
        if balance < 0:
            raise ValueError('Starting balance cannot be negative')
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        """Current balance, read-only through the public interface."""
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError('Deposit must be positive')
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError('Withdrawal must be positive')
        if amount > self._balance:
            raise ValueError('Insufficient funds')
        self._balance -= amount
        return self

    def __str__(self):
        return f"BankAccount(owner={self.owner}, balance=${self._balance:.2f})"

    def __repr__(self):
        return f"BankAccount({self.owner!r}, {self._balance!r})"

    @staticmethod
    def parse_record(s):
        """Parse an 'owner:balance' record into raw values."""
        owner, balance = s.split(':')
        return owner, float(balance)

Because parse_record is a static method, it has no self or cls parameter. It is a utility helper that can be called on the class directly:

owner, balance = BankAccount.parse_record("Taylor:348.00")
acct = BankAccount(owner, balance)
print(acct)   # BankAccount(owner=Taylor, balance=$348.00)
BankAccount(owner=Taylor, balance=$348.00)

9.3.6.2. Class Methods#

A class method receives the calling class as its first argument, conventionally named cls. Writing cls(...) selects that class when constructing a result, including an inheriting subclass. It succeeds only if that class accepts the arguments being supplied.

The owner/balance version below keeps the balance validation, read-only property, and update return values from OOP Design and Methods. It does not use the numbered constructor from The Four Pillars. The alternative constructors delegate validation to __init__ instead of duplicating it.

class BankAccount:
    """A teaching account with controlled balance updates."""

    def __init__(self, owner="Unknown", balance=0.0):
        if balance < 0:
            raise ValueError('Starting balance cannot be negative')
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        """Current balance, read-only through the public interface."""
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError('Deposit must be positive')
        self._balance += amount
        return self

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError('Withdrawal must be positive')
        if amount > self._balance:
            raise ValueError('Insufficient funds')
        self._balance -= amount
        return self

    def __str__(self):
        return f"BankAccount(owner={self.owner}, balance=${self._balance:.2f})"

    def __repr__(self):
        return f"BankAccount({self.owner!r}, {self._balance!r})"

    @classmethod
    def from_string(cls, s):
        """Create an account from an 'owner:balance' record."""
        owner, balance = s.split(':')
        return cls(owner, float(balance))

    @classmethod
    def zero_balance(cls, owner):
        return cls(owner, 0.0)
acct1 = BankAccount.from_string("Taylor:348.00")
print(acct1)  # BankAccount(owner=Taylor, balance=$348.00)
BankAccount(owner=Taylor, balance=$348.00)
# Alternative constructors for the owner/balance version
acct1 = BankAccount.from_string("Casey:94.50")
acct2 = BankAccount.zero_balance("Rin")
print(acct1)   # BankAccount(owner=Casey, balance=$94.50)
print(acct2)   # BankAccount(owner=Rin, balance=$0.00)
BankAccount(owner=Casey, balance=$94.50)
BankAccount(owner=Rin, balance=$0.00)

When to use which:

Question

@staticmethod

@classmethod

Implicit receiver

None

Calling class (cls)

How can it obtain state?

Explicit arguments or named objects

Class receiver, plus explicit arguments

Typical use here

Parse a record into values

Construct an instance of the calling class

A static method does not inherently hardcode a parent class. A class method is useful for a factory that should follow inheritance, but it cannot adapt automatically to an incompatible initializer. Preserve the factory contract or override the factory in a subclass that needs additional information.

Compare two subclasses. The first inherits a compatible initializer. The second requires a tier that the inherited factory cannot supply. Predict the type of the first result and the exception for the second call.

class BasicAccount(BankAccount):
    pass

created = BasicAccount.from_string('Ava:100')
print(type(created) is BasicAccount)  # True

class TieredAccount(BankAccount):
    def __init__(self, owner, balance, tier):
        super().__init__(owner, balance)
        self.tier = tier

try:
    TieredAccount.from_string('Ava:100')
except TypeError:
    print('The inherited factory cannot supply tier')
True
The inherited factory cannot supply tier
### Exercise: Class Methods
#   Create a subclass ExtendedBankAccount(BankAccount) and add a class
#   method from_balance_str(cls, owner, s) that parses a dollar string
#   like "12.34" and returns a new account.
#   Test:
#       acct = ExtendedBankAccount.from_balance_str("Kai", "12.34")
#       print(acct)
#       print(type(acct).__name__)   # ExtendedBankAccount
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class ExtendedBankAccount(BankAccount):
    @classmethod
    def from_balance_str(cls, owner, s):
        """Create account from a balance string like '12.34'."""
        return cls(owner, float(s))

acct = ExtendedBankAccount.from_balance_str("Kai", "12.34")
print(acct)                  # __str__ is inherited from BankAccount
print(type(acct).__name__)   # but cls built the subclass
BankAccount(owner=Kai, balance=$12.34)
ExtendedBankAccount

9.3.7. Exercises#

This task combines a dataclass, operator overloading, and static and class methods in one record type.

### Exercise: Advanced OOP Review
#   Build one record type that uses several features from this section.
#   1. Import dataclass and define @dataclass(order=True) class Payment with
#      fields amount: float and payer: str, in that order.
#   2. Add a static method is_valid_amount(amount) that returns True when
#      the amount is positive.
#   3. Add a class method from_record(cls, record) that splits a record such as
#      "Ava:40.0" at the colon, converts the amount to float, raises ValueError
#      if is_valid_amount returns False, and returns cls(amount, payer).
#   4. Add __add__ that returns a new Payment whose amount is the sum and whose
#      payer is "combined". Return NotImplemented for any other operand type.
#   5. Create p1 = Payment.from_record("Ava:40.0") and
#      p2 = Payment.from_record("Ben:25.5"). Print the payers in sorted order,
#      p1 + p2, and both original amounts.
#   6. Call Payment.from_record("Cy:-5") inside try/except ValueError and
#      print "Invalid amount". Expected output:
#      Sorted payers: ['Ben', 'Ava']
#      Combined: Payment(amount=65.5, payer='combined')
#      Originals: 40.0 25.5
#      Invalid amount
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from dataclasses import dataclass

@dataclass(order=True)
class Payment:
    amount: float
    payer: str

    @staticmethod
    def is_valid_amount(amount):
        return amount > 0

    @classmethod
    def from_record(cls, record):
        payer, amount = record.split(':')
        amount = float(amount)
        if not cls.is_valid_amount(amount):
            raise ValueError('Amount must be positive')
        return cls(amount, payer)

    def __add__(self, other):
        if not isinstance(other, Payment):
            return NotImplemented
        return Payment(self.amount + other.amount, 'combined')

p1 = Payment.from_record('Ava:40.0')
p2 = Payment.from_record('Ben:25.5')
print('Sorted payers:', [p.payer for p in sorted([p1, p2])])
print('Combined:', p1 + p2)
print('Originals:', p1.amount, p2.amount)

try:
    Payment.from_record('Cy:-5')
except ValueError:
    print('Invalid amount')
Sorted payers: ['Ben', 'Ava']
Combined: Payment(amount=65.5, payer='combined')
Originals: 40.0 25.5
Invalid amount