9.2. The Four Pillars of OOP#

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

Basic underscore conventions are part of the core reading because the examples use them. The detailed Name Mangling dropdown is optional.

Object-oriented programming is often organized around four big ideas known as the four pillars of OOP. These pillars are not strict rules that every class must follow in the same way. Instead, they are design principles that help you build programs that are easier to understand, extend, and maintain.

When people say a program is “object-oriented,” they usually mean that classes and objects are used to organize related data together with the operations that act on that data. The four pillars give you a vocabulary for describing how that organization works.

As you read each section, keep three questions in mind:

  • What problem does this pillar solve?

  • What does the Python code gain by using it?

  • What would the code look like without it?

Pillar

Core idea

Encapsulation

Bundle data and behavior together, and protect internal state

Polymorphism

Use a common interface even when different classes behave differently

Inheritance

Build a new class by reusing and extending an existing one

Abstraction

Show what an object can do without exposing every implementation detail

In practice, these ideas overlap. A class might use encapsulation to protect its data, inheritance to reuse behavior, polymorphism to work with many object types, and abstraction to present a simple public interface. This section treats them separately so each one is easier to see.

Encapsulation comes first because it is one of the most immediate and practical ideas in everyday Python class design.

The table below compares the four pillars side by side: what each one is for, what it focuses on, the design level where it works, and the Python tools that usually express it.

Aspect

Encapsulation

Polymorphism

Inheritance

Abstraction

Core Intent

Hide data/state. Groups data and behavior, restricting direct outside access.

Enable flexibility. Allows a single interface or method name to handle multiple types.

Reuse code. Passes down properties and behaviors from an existing class to a new one.

Hide complexity. Shows only the essential features of a component.

Focus

How an object protects its data integrity internally.

Which specific type or behavior a method takes during execution.

Who an object is in relation to others (the relationship hierarchy).

What an object does, rather than how it does it.

Design Level

Low-level implementation. Restricting access and variables within the class code.

Runtime/Execution. Deciding which specific code execution path to take dynamically.

Structural/Relational. Organizing code into logical parent-child trees (IS-A relationships).

High-level architectural/conceptual. Defining the overall contract of software components.

Python Tools

• Underscore names (_balance, __salary)
• @property for controlled access
• Methods that validate changes

• Method overriding
• Duck typing
• Special methods (__str__)

• class Child(Parent):
• super()
• Mixins

• Abstract base classes (abc.ABC, @abstractmethod)
• A small set of public methods

9.2.1. Encapsulation#

Downsides of Python (0:31) by Ryan Peterman
Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Encapsulation means that an object manages its own state (its data at a point in time) by keeping related data and behavior together and by controlling how that data is accessed or changed.

This idea has two parts:

  • A class bundles attributes and methods into one coherent unit.

  • A class protects its internal state so values are changed in deliberate, valid ways rather than arbitrarily from outside the object.

Encapsulation connects to several important ideas in software engineering:

  • Bundling: Grouping data and methods into one unit, the class.

  • Information Hiding: Restricting access to internal state. Python does this via convention and consensus.

  • Abstraction: the class can expose a simple public interface while hiding implementation details.

  • Data integrity: the class can validate updates and keep the object in a consistent state.

In Python, encapsulation is based on conventions and interface design rather than strict access control such as the private keyword to block access as in Java. This is achieved by using underscores to signal intent to other developers:

  • _variable (Internal by convention): A single underscore tells other programmers, “internal use by convention”, meaning “This is internal; use it at your own risk because it might change.” Python won’t stop you from accessing it, but doing so is considered bad practice.

  • __variable (Name-mangled): A double underscore triggers Name Mangling. It reduces accidental name collisions with subclasses, but does not provide access security. The optional note below explains the rewritten spelling.

The main goal of encapsulation is to make callers depend on the object’s public interface, not on the details of how the object stores or computes its data.

Consider a payroll system. An employee’s name is usually safe to expose directly, but salary updates need a controlled interface to keep values valid. Naming conventions and properties do not provide confidentiality. The example below stores the salary in a double-underscore attribute, exposes it through a read-only @property, and makes give_raise() the only way to change it.

class Employee:
    def __init__(self, name, salary):
        if salary < 0:              ### simple validation check salary is not negative
            raise ValueError('Salary cannot be negative')

        self.name = name            ### public attribute
        self.__salary = salary      ### double underscore triggers name mangling; this is meant
                                    ### for internal use and should not be accessed directly
                                    ### from outside the class.

    @property                       ### use property to expose salary through a controlled read-only interface.
    def salary(self):               ###
        return self.__salary

    def give_raise(self, percent):  ### the one controlled way to change salary
        if percent <= 0:
            raise ValueError('Raise must be positive')
        self.__salary = round(self.__salary * (1 + percent / 100), 2)
        return self

emp = Employee('Frederick', 50000)
print(emp.name)
print(emp.salary)   ### this calls the salary method, but you access it like an attribute (no parentheses)
                    #   because of the @property decorator.

emp.give_raise(10)
print(emp.salary)   # 55000.0
try:
    emp.give_raise(-5)
except ValueError as error:
    print(error)    # Raise must be positive
Frederick
50000
55000.0
Raise must be positive

The same encapsulation idea appears in banking systems. A bank account should not allow outside code to change the balance arbitrarily; instead, the class should expose controlled operations such as deposit and withdraw, along with a read-only way to inspect the current balance.

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})"

acct = BankAccount('Alice', 100)
acct.deposit(50)
acct.withdraw(30)
print(acct.balance)  # 120
120

9.2.1.1. Access Level Conventions#

Python does not enforce strict access modifiers like Java or C++. Instead, it uses naming patterns to communicate intent:

  • name: public

  • _name: internal use by convention

  • __name: triggers name mangling to reduce accidental access or accidental override in subclasses

That last point matters: double underscore is more than a social convention. Python actually rewrites the attribute name internally. It is still not true private security, but it does provide stronger protection against accidental misuse than a single underscore.

In the examples above:

  • Employee.__salary shows double-underscore name mangling.

  • BankAccount._balance shows an internal attribute exposed safely through methods and @property.

See the note below for how name mangling works.

### Exercise: Encapsulation
#   1. Define a class Customer with a public attribute name and a
#      name-mangled attribute __pin, both set in __init__.
#   2. Add a read-only property masked_pin that returns '**' followed by
#      the last two characters of the PIN.
#   3. Add a method check_pin(pin) that returns True if pin matches __pin.
#   4. Create c = Customer('Ava', '4821'). Print c.name, c.masked_pin,
#      c.check_pin('0000'), and c.check_pin('4821').
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class Customer:
    def __init__(self, name, pin):
        self.name = name
        self.__pin = pin

    @property
    def masked_pin(self):
        return '**' + self.__pin[-2:]

    def check_pin(self, pin):
        return pin == self.__pin

c = Customer('Ava', '4821')
print(c.name)
print(c.masked_pin)
print(c.check_pin('0000'))
print(c.check_pin('4821'))
Ava
**21
False
True

9.2.2. Polymorphism#

Polymorphism means different object types can respond to the same method call in their own way.

In the banking example below, each account type implements the same method, month_end(). The caller does not need if/elif logic for each account type; it calls one method name on all accounts.

The next three classes do not share a parent class, and they are not the BankAccount class from above. Each one stores a public balance and provides its own month_end() method.

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

    def month_end(self):
        self.balance -= 10   # monthly service fee


class InterestAccount:
    def __init__(self, owner, balance, rate=0.01):
        self.owner = owner
        self.balance = balance
        self.rate = rate

    def month_end(self):
        self.balance += self.balance * self.rate   # monthly interest


class LoanAccount:
    def __init__(self, owner, balance, rate=0.015):
        self.owner = owner
        self.balance = balance
        self.rate = rate

    def month_end(self):
        self.balance += self.balance * self.rate   # interest on amount owed


accounts = [                        ### a list of different account types
    CheckingAccount('Alice', 1200), ### each one can run month_end(), whatever its class
    InterestAccount('Bob', 5000),
    LoanAccount('Charlie', 2000),
]
print('Before month-end:')
for account in accounts:
    print(f'{account.owner}: {account.balance:.2f}')
Before month-end:
Alice: 1200.00
Bob: 5000.00
Charlie: 2000.00

All objects in accounts provide month_end(), so one uniform loop can apply month-end updates . No type-specific if/elif branches are needed.

for account in accounts:
    account.month_end()   # polymorphic call

print('\nAfter month-end:')
for account in accounts:
    print(f'{account.owner}: {account.balance:.2f}')
After month-end:
Alice: 1190.00
Bob: 5050.00
Charlie: 2030.00

In this loop, account can be a CheckingAccount, InterestAccount, or LoanAccount, but the caller code is identical:

account.month_end()

Python dispatches to the correct class-specific implementation at runtime. That is the core idea of polymorphism: one interface, many behaviors.

The three classes share no parent class. The loop works only because each object has a month_end() method. Python checks for the method when the call happens, not for the object’s type. This style is called duck typing: if an object can do what the code asks, its class does not matter. Inheritance and abstract base classes, later in this section, make a shared interface explicit, but Python polymorphism does not require them.

### Exercise: Banking Polymorphism
#   The classes CheckingAccount, InterestAccount, and LoanAccount are already defined above.
#
#   1. Define a new class InvestmentAccount with:
#         - __init__(self, owner, balance, rate=0.02)
#         - month_end(self) that first adds interest at self.rate and then
#           subtracts a $5 management fee
#
#   2. Create one instance of each of the four account types:
#         CheckingAccount('Alice', 1200)
#         InterestAccount('Bob', 5000)
#         LoanAccount('Charlie', 2000)
#         InvestmentAccount('Diana', 3000, 0.02)
#
#   3. Put all four in a list called accounts.
#   4. Loop over accounts and call month_end() on each one.
#   5. Loop again and print each owner's updated balance.
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
class InvestmentAccount:
    def __init__(self, owner, balance, rate=0.02):
        self.owner = owner
        self.balance = balance
        self.rate = rate

    def month_end(self):
        self.balance += self.balance * self.rate   # interest first
        self.balance -= 5                          # then the management fee

accounts = [
    CheckingAccount('Alice', 1200),
    InterestAccount('Bob', 5000),
    LoanAccount('Charlie', 2000),
    InvestmentAccount('Diana', 3000, 0.02),
]

for account in accounts:
    account.month_end()

for account in accounts:
    print(f'{account.owner}: {account.balance:.2f}')
Alice: 1190.00
Bob: 5050.00
Charlie: 2030.00
Diana: 3055.00

9.2.3. Inheritance#

The language feature most often associated with object-oriented programming is inheritance. Inheritance lets you define a new class as a modified or specialized version of an existing class.

When inheritance is used well, it helps you avoid rewriting code that is already correct in the parent class. The child class reuses what it needs and adds or overrides only the parts that make it different.

The examples in this section use bank accounts. That domain is close to the kinds of systems used in business settings, but the main idea is general: a child class can reuse behavior from a parent class and then extend it for a more specific purpose.

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

    def __init__(self, account_number, owner, balance=0.0):
        if balance < 0:
            raise ValueError('Starting balance cannot be negative')
        self.account_number = account_number
        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'{self.account_number}: {self.owner} - ${self.balance:.2f}'

    def transfer_to(self, other_account, amount):
        if not isinstance(other_account, BankAccount):
            raise TypeError('Transfers require another BankAccount')
        self.withdraw(amount)
        other_account.deposit(amount)
        return self

A subclass is defined with the same class statement as any other class. The difference is that the parent class name appears in parentheses after the subclass name.

The examples in this section use a new version of BankAccount whose constructor takes an account_number before the owner. It keeps the same rules as before: a nonnegative starting balance, a read-only public balance, positive update amounts, and deposit() and withdraw() returning the account.

Use inheritance when the child should support the parent’s public operations. A subclass can add a rate or a withdrawal rule while keeping callers’ expectations about balance access and update results. Redefining a class with the same name replaces it for newly created objects; it does not change objects created earlier.

9.2.3.1. Parents and children#

Inheritance is the ability to define a new class that is a modified version of an existing class. A useful banking example is a SavingsAccount, which is a specific kind of BankAccount.

  • A savings account is similar to a general bank account because it still has an owner, an account number, a balance, and common operations such as deposit and withdrawal, which you can reuse instead of defining them again.

  • A savings account is also different because it has behavior that does not apply to every account type. For example, it earns interest at its own rate. The version below stores that rate in the child class; a method that uses it would be added the same way BusinessAccount adds withdraw_with_fee() later in this section.

This relationship between classes, where one is a specialized version of another, lends itself naturally to inheritance. To define a new class that is based on an existing class, the name of the existing class is placed in parentheses.

The basic pattern for Python syntax for inheritance is:

class Parent:
    def __init__(self, x):
        self.x = x

class Child(Parent):
    def __init__(self, x, y):
        super().__init__(x)   # call Parent.__init__
        self.y = y

In this pattern, Child is the subclass and Parent is the superclass. To create an inheritance relation for the example below (BankAccount is the parent class and SavingsAccount is the child class),

class SavingsAccount(BankAccount):
    pass                        ### no code needed but can't leave it blank

The next cell defines SavingsAccount as a child class of BankAccount.

class SavingsAccount(BankAccount):
    """Represents a savings account."""

    def __init__(self, account_number, owner, balance=0.0, rate=0.01):
        super().__init__(account_number, owner, balance)    ### # call Parent.__init__ to initialize the common attributes
        self.rate = rate    ### extra attribute specific to SavingsAccount

This definition indicates that SavingsAccount inherits from BankAccount, which means that SavingsAccount objects can access methods defined in BankAccount, like deposit and withdraw.

SavingsAccount also inherits __init__ from BankAccount, but if you define __init__ in the SavingsAccount class, it overrides the one in the BankAccount class.

Note that:

  • SavingsAccount is a subclass of BankAccount because BankAccount is in parentheses of the header of SavingsAccount.

  • there is a __init__ constructor here and it has all the parameters the parent class has and an additional parameter rate=.

  • super().__init__(...) reuses the parent initializer to set up the account number, owner, and balance.

  • the child then initializes its specialized attribute: rate, which does not exist in the parent class.

This version of __init__ takes the same basic account information as the parent class and adds an interest rate. When a SavingsAccount is created, Python invokes this method, but super().__init__(...) reuses the parent setup so the shared attributes do not have to be written again.

savings = SavingsAccount('S-1001', 'Ava', 1200.00, rate=0.02)
print(savings.rate)
0.02

Because SavingsAccount inherits from BankAccount, it can use methods defined in the parent class without redefining them. The next example calls deposit method, which was written once in BankAccount and then reused by the child class.

savings.deposit(300.00)                 ### inherited method from BankAccount
print(savings)
print(isinstance(savings, SavingsAccount))
print(isinstance(savings, BankAccount))
S-1001: Ava - $1500.00
True
True

The parent class also defines a method that is shared by every kind of bank account. A transfer operation belongs in the parent class because it is useful for a regular bank account, a savings account, and any future subclass that behaves like a bank account.

    def transfer_to(self, other_account, amount):
        if not isinstance(other_account, BankAccount):
            raise TypeError('Transfers require another BankAccount')
        self.withdraw(amount)
        other_account.deposit(amount)
        return self

This method is defined once in the parent class, but it can be used by any child class that inherits from BankAccount. That is one of the main advantages of inheritance: common behavior lives in one place instead of being duplicated across several related classes.

A child class is often called a subclass, and the parent class is often called a superclass. In this example, SavingsAccount is a subclass of BankAccount, and BankAccount is a superclass of SavingsAccount.

A SavingsAccount should be usable anywhere a BankAccount is expected because it still supports the same core account behaviors. That idea makes inheritance practical: the parent class defines what related objects have in common, and the child class adds what makes it special.

9.2.3.2. Specialization#

Inheritance becomes especially useful when subclasses need to keep the basic behavior of the parent class but also add rules of their own. A BusinessAccount, for example, is still a bank account, but it may charge a service fee for certain withdrawals. That makes it a good example of specialization.

class BusinessAccount(BankAccount):
    """Represents a business checking account."""

    def __init__(self, account_number, owner, balance=0.0, transaction_fee=5.0):
        super().__init__(account_number, owner, balance)
        if transaction_fee < 0:
            raise ValueError('Transaction fee cannot be negative')
        self.transaction_fee = transaction_fee

    def withdraw_with_fee(self, amount):
        if amount <= 0:
            raise ValueError('Withdrawal must be positive')
        total = amount + self.transaction_fee
        self.withdraw(total)
        return total

The withdraw_with_fee method deducts both the requested withdrawal amount and the transaction fee from the account balance.

biz = BusinessAccount('B-1001', 'Acme Corp', 1000.0)    ### 1000 in initial balance
total = biz.withdraw_with_fee(200)
print(f'Withdrawn: $200.00, Fee: ${biz.transaction_fee:.2f}, Total deducted: ${total:.2f}')
print(biz)
Withdrawn: $200.00, Fee: $5.00, Total deducted: $205.00
B-1001: Acme Corp - $795.00

The withdraw_with_fee method belongs in the child class because the extra fee is specific to business accounts, not to every kind of bank account.

On the other hand, the transfer_to() method is in the superclass so that the subclasses can use them.

business = BusinessAccount('B-2001', 'Northwind Supply', 5000.00, transaction_fee=12.50)
personal = SavingsAccount('S-2002', 'Mina', 1800.00, rate=0.03)

business.transfer_to(personal, 400.00)
print(business)
print(personal)
B-2001: Northwind Supply - $4600.00
S-2002: Mina - $2200.00

The same business account can also make a fee-based withdrawal. withdraw_with_fee() takes only the amount; the fee comes from the account itself, which was created with transaction_fee=12.50.

charged = business.withdraw_with_fee(250.00)
print(f'Total charged: ${charged:.2f}')
print(business)
Total charged: $262.50
B-2001: Northwind Supply - $4337.50

withdraw_with_fee subtracts both the withdrawal amount and the fee, while the inherited methods from BankAccount still handle the core balance updates.

business.balance
4337.5

In this example, BusinessAccount inherited general account behavior from BankAccount and then added specialized behavior of its own. The child class did not need to rewrite deposit, basic withdrawal, string display, or transfer logic.

The SavingsAccount and BusinessAccount classes inherited all the methods from BankAccount, such as deposit, withdraw, __str__, and transfer_to, but each subclass also gained attributes or methods that reflect its own role in the banking system.

9.2.3.3. issubclass()#

The issubclass() checks whether one class inherits from another at runtime.

issubclass(Child, Parent) returns True if Child is a subclass of Parent or is Parent itself. It is useful when class relationships need to be checked at runtime.

A practical detail matters here: the first argument to issubclass() must itself be a class. If user input or function arguments are being validated, that point is often worth checking explicitly before calling issubclass().

Function

Checks

isinstance(obj, cls)

Is obj an instance of cls or one of its subclasses?

issubclass(A, B)

Is class A a subclass of B?

class Animal:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound

    def speak(self):
        return f'{self.name} says {self.sound}!'

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, sound='Woof')
        self.breed = breed

    def info(self):
        return f'{self.name} is a {self.breed}'
print(issubclass(Dog, Animal))   # True
print(issubclass(Animal, Dog))   # False
print(issubclass(Dog, Dog))      # True (a class is a subclass of itself)

# Common use: guarding against wrong arguments
def make_animal(cls, *args, **kwargs):
    if not isinstance(cls, type):
        raise TypeError('cls must be a class')
    if not issubclass(cls, Animal):
        raise TypeError(f'{cls} is not an Animal subclass')
    return cls(*args, **kwargs)

rex = make_animal(Dog, 'Rex', 'Labrador')
print(rex.speak())   # Rex says Woof!
True
False
True
Rex says Woof!

9.2.3.4. Class Variables#

A class can also store values in its class body, such as a bank name or a default transfer fee. Every instance shares these class variables, and every subclass inherits them:

class Animal:
    kingdom = 'Animalia'      # class variable, shared by every Animal

class Dog(Animal):
    pass

print(Dog.kingdom)       # inherited from Animal
print(Dog().kingdom)     # an instance sees it too
Animalia
Animalia

Advanced OOP covers class variables in full, including what happens when an instance assigns to one.

9.2.3.5. Method Overriding#

An override happens when a child class defines a method with the same name as a parent method to change or specialize behavior.

A common pattern is:

  • add child-specific validation or rules

  • then call super().method(...) to reuse the parent logic

This keeps shared behavior in one place while still allowing specialization.

class LimitedSavingsAccount(SavingsAccount):
    def __init__(self, account_number, owner, balance=0.0, rate=0.01, min_balance=100.0):
        super().__init__(account_number, owner, balance, rate)
        self.min_balance = min_balance

    def withdraw(self, amount):
        # Child-specific rule before parent logic
        if self.balance - amount < self.min_balance:
            raise ValueError(f'Cannot go below minimum balance of ${self.min_balance:.2f}')
        return super().withdraw(amount)  # preserve the parent return contract

lsa = LimitedSavingsAccount('S-9001', 'Nina', 500.0, rate=0.02, min_balance=200.0)
lsa.withdraw(250)
print(lsa)

try:
    lsa.withdraw(100)
except ValueError as e:
    print(e)
S-9001: Nina - $250.00
Cannot go below minimum balance of $200.00

The child checks its minimum-balance rule, then delegates to the parent’s positive-amount and funds checks. Neither version subtracts before validating. Returning the parent’s result preserves the withdraw() contract, so inherited callers need not change how they use a successful update.

### Exercise: Inheritance
#   1. Define a parent class Account with owner and balance in __init__,
#      a withdraw(amount) method that raises ValueError('Insufficient funds')
#      if amount > balance, and a __str__ that returns 'owner: $balance'.
#   2. Define a child class StudentAccount(Account) that:
#         - adds a school attribute, using super().__init__() for the rest
#         - overrides withdraw(amount) to raise ValueError if amount > 200,
#           then calls super().withdraw(amount)
#   3. Create s = StudentAccount('Leo', 500, 'State U') and call s.withdraw(150).
#   4. Print s, then try s.withdraw(250) and print the error message.
#   5. Print isinstance(s, Account) and issubclass(StudentAccount, Account).
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
class Account:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError('Insufficient funds')
        self.balance -= amount

    def __str__(self):
        return f'{self.owner}: ${self.balance:.2f}'

class StudentAccount(Account):
    def __init__(self, owner, balance, school):
        super().__init__(owner, balance)
        self.school = school

    def withdraw(self, amount):
        if amount > 200:
            raise ValueError('Student accounts can withdraw at most $200 at a time')
        super().withdraw(amount)

s = StudentAccount('Leo', 500, 'State U')
s.withdraw(150)
print(s)

try:
    s.withdraw(250)
except ValueError as e:
    print(e)

print(isinstance(s, Account))
print(issubclass(StudentAccount, Account))
Leo: $350.00
Student accounts can withdraw at most $200 at a time
True
True

9.2.4. Abstraction#

Abstraction means exposing what an object can do while hiding how it does it. Callers interact with a clean public interface and never need to know the internal logic. For example, you can call sorted() without knowing Python’s sorting algorithm, use list.append() without knowing how lists are stored in memory, or call acct.deposit() without knowing what happens inside. Good abstraction makes complex systems feel simple.

While inheritance provides a mechanism for one class to reuse another’s code, abstraction is a design goal for hiding complexity behind a simple interface.

Here the BankAccount class is a good example. A caller using deposit, withdraw, or transfer_to does not need to know:

  • how withdraw validates the amount

  • how transfer_to coordinates two accounts

  • how _balance is stored internally

The caller only needs the interface: the method names and what they do.

eve_savings  = SavingsAccount('S-3001', 'Eve', 2000.00, rate=0.02)
eve_business = BusinessAccount('B-3001', 'Eve Co', 5000.00, transaction_fee=8.0)

# None of these callers need to know the internal validation or storage logic
eve_savings.deposit(500)
eve_business.withdraw(300)
eve_business.transfer_to(eve_savings, 1000)

print(eve_savings)
print(eve_business)
S-3001: Eve - $3500.00
B-3001: Eve Co - $3700.00

9.2.4.1. Abstract Base Classes (abc)#

Python supports abstraction explicitly through the built-in abc module (Abstract Base Classes). An Abstract Base Class (ABC) formalizes that pattern by declaring a contract: any subclass must implement certain methods. Calling an abstract class, or a subclass that is missing one of those methods, raises a TypeError instead of creating an object. In other words, with ABC, an abstract base class defines a required interface, it declares methods that child classes must implement.

To implement ABC, you need to import the ABC class and the abstractmethod decorator.

from abc import ABC, abstractmethod

class Account(ABC):
    @abstractmethod
    def month_end(self):
        """Apply end-of-month rules for this account type."""
        pass

In this design, Account is not meant to be instantiated directly. Instead, concrete subclasses such as SavingsAccount or CheckingAccount provide their own implementation of month_end().

After a class inherits from an ABC, two behavior rules matter:

  • The subclass must implement every abstract method before it can be instantiated.

  • Any function that expects the ABC type can use different subclasses interchangeably through the same method names.

ABC is useful when you want to enforce a shared interface across related classes, not just rely on convention.

# Use case: unified payment processing interface with ABC
from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod                 ### this decorator marks charge as an abstract method 
    def charge(self, amount):       ### that must be implemented by subclasses
        """Return a message describing how payment is processed."""
        pass

class CreditCard(PaymentMethod):
    def __init__(self, last4):
        self.last4 = last4

    def charge(self, amount):       ### this method implements the abstract charge method defined in PaymentMethod
        return f"Charged ${amount:.2f} to card ending in {self.last4}."

class PayPal(PaymentMethod):        ### another concrete implementation of PaymentMethod
    def __init__(self, email):
        self.email = email

    def charge(self, amount):
        return f"Charged ${amount:.2f} via PayPal account {self.email}."


def checkout(payment_method, amount):
    if not isinstance(payment_method, PaymentMethod):
        raise TypeError("checkout requires a PaymentMethod")
    return payment_method.charge(amount)

methods = [CreditCard("4242"), PayPal("student@example.com")]
for method in methods:
    print(checkout(method, 49.99))
Charged $49.99 to card ending in 4242.
Charged $49.99 via PayPal account student@example.com.

In the example above, both CreditCard and PayPal inherit from PaymentMethod, so each one must provide charge(self, amount).

That gives two practical benefits:

  • checkout(...) depends only on the abstract interface, not on a specific concrete class.

  • New payment types can be added later (for example, GiftCard or BankTransfer) without changing checkout(...), as long as they inherit from PaymentMethod and implement charge(...).

This is abstraction in action: one stable contract, many concrete behaviors.

### Exercise: Abstraction
#   1. Define an abstract class PaymentMethod(ABC) with an abstract
#      method charge(self, amount).
#   2. Define a concrete class GiftCard(PaymentMethod) with code and balance.
#      Its charge(amount) raises ValueError if amount > balance; otherwise it
#      subtracts amount and returns a message such as
#      'Charged $20.00 to gift card GC-77; $30.00 left.'
#   3. Try to create PaymentMethod() inside try/except TypeError and print
#      'Cannot instantiate PaymentMethod'.
#   4. Create GiftCard('GC-77', 50.0) and print the result of charge(20).
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from abc import ABC, abstractmethod

class PaymentMethod(ABC):
    @abstractmethod
    def charge(self, amount):
        pass

class GiftCard(PaymentMethod):
    def __init__(self, code, balance):
        self.code = code
        self.balance = balance

    def charge(self, amount):
        if amount > self.balance:
            raise ValueError('Gift card balance too low')
        self.balance -= amount
        return f'Charged ${amount:.2f} to gift card {self.code}; ${self.balance:.2f} left.'

try:
    PaymentMethod()
except TypeError:
    print('Cannot instantiate PaymentMethod')

card = GiftCard('GC-77', 50.0)
print(card.charge(20))
Cannot instantiate PaymentMethod
Charged $20.00 to gift card GC-77; $30.00 left.

9.2.5. Exercises#

This task combines all four pillars in one small design.

### Exercise: Four Pillars Review
#   Create a small OOP example that demonstrates all four pillars.
#   1. Define class Wallet with owner and _cash, plus a read-only cash property.
#   2. Add deposit(amount) and spend(amount) methods.
#      If spend amount is greater than _cash, raise ValueError.
#   3. Define class SavingsWallet(Wallet) that adds apply_interest(rate).
#   4. Define abstract class Notifier with abstract method send(amount).
#      Implement EmailNotifier and SMSNotifier, each returning a message string.
#   5. Create one SavingsWallet, call deposit, spend, and apply_interest.
#   6. Put both notifier types in one list and call send(w.cash) in one loop.
#   7. Print wallet cash and both notifier messages.
### Your code starts here.


### Your code ends here.

Hide code cell source

### Solution
from abc import ABC, abstractmethod

class Wallet:
    def __init__(self, owner, cash=0.0):
        self.owner = owner
        self._cash = float(cash)

    @property
    def cash(self):
        return self._cash

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

    def spend(self, amount):
        if amount > self._cash:
            raise ValueError("Not enough cash")
        self._cash -= amount

class SavingsWallet(Wallet):
    def apply_interest(self, rate):
        self._cash += self._cash * rate

class Notifier(ABC):
    @abstractmethod
    def send(self, amount):
        pass

class EmailNotifier(Notifier):
    def send(self, amount):
        return f"Email sent: wallet balance is ${amount:.2f}"

class SMSNotifier(Notifier):
    def send(self, amount):
        return f"SMS sent: wallet balance is ${amount:.2f}"

w = SavingsWallet("Lia", 100.0)
w.deposit(25.0)
w.spend(40.0)
w.apply_interest(0.10)

print(w.cash)
for notifier in [EmailNotifier(), SMSNotifier()]:
    print(notifier.send(w.cash))
93.5
Email sent: wallet balance is $93.50
SMS sent: wallet balance is $93.50