Skip to main content

5.1 Classes and Objects

Python classes bundle data and behavior with minimal syntax overhead.

Basic class pattern

class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance

def deposit(self, amount):
self.balance += amount

Important OOP semantics

  • Instance methods receive the instance as first parameter (conventionally self).
  • Class attributes are shared; instance attributes are per-object.
  • Attribute lookup checks instance first, then class, then base classes.

Inheritance and super()

class SavingsAccount(BankAccount):
def __init__(self, owner, balance=0, rate=0.03):
super().__init__(owner, balance)
self.rate = rate

Python uses method resolution order (MRO), especially relevant with multiple inheritance.

Iterators and generators in class design

  • Iteration uses iter(obj) and next(iterator) protocols.
  • Generator methods can yield values lazily and simplify iteration logic.

Official references