1class BankAccount:2 def __init__(self, owner):3 self.owner = owner4 self._balance = 05 def deposit(self, amount):6 self._balance += amount7 def withdraw(self, amount):8 if amount > self._balance:9 raise ValueError10 self._balance -= amounta · BankAccountowner_balanceb · BankAccountowner_balance1class Savings(BankAccount):2 def withdraw(self, amount):3 super().withdraw(amount + 1)s · Savingsowner_balancebank · BankaccountsabsValueError
Code cards: the class BankAccount and its subclass Savings; highlighted lines are runningObjects: one slab per object, with its own attribute cellsLinks: the bank's references to the accounts it hasToken: the value a running line hands to an objectThe class card is the blueprint; each object built from it gets its own owner and _balance cells. Each step highlights the lines of code that run, and a value token hops from them to the object they change. Methods live once, on the class; a call runs them with self set to the object. Savings inherits from BankAccount and overrides withdraw, so the same call gives different results on a and s. The bank holds links to the accounts: it has them, it is not one. The fee of 1 on Savings withdrawals is invented for the example.

Classes and objects

  1. A class is a blueprint. The class line and the indented lines under it describe what every bank account will hold and what it can do. Running it makes no account yet, so nothing holds money.

Methods and encapsulation

Inheritance

Polymorphism and composition

Try it in the Python prompt

;; step 1/10 · class BankAccount:
>>> class BankAccount:
...     ...          # the ten lines on the card
>>> BankAccount
<class '__main__.BankAccount'>

a.deposit(50) is exactly equivalent to BankAccount.deposit(a, 50). That is why every method's first parameter, named self by convention, receives the object the method was called on. Python has no truly private attributes. A leading underscore, as in _balance, is a convention that marks a non-public part: code outside can still reach a._balance, but should not. The cards indent by two spaces so each line fits. Python only needs the indentation to be consistent; the style guide PEP 8 recommends four spaces.