Skip to main content

Python OOP

Abstraction

Complete lesson for Abstraction using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Abstraction

Section: Python OOP. Show what an object does and hide how — abc.ABC, @abstractmethod, Protocols, and duck typing.

What is abstraction?

  • Abstraction exposes essential operations and hides implementation details.
  • Callers depend on “what” (start(), pay()), not “how”.
  • In Python you use ABCs (abc module), Protocols, or informal duck typing.
from abc import ABC, abstractmethod


class Vehicle(ABC):
    @abstractmethod
    def start(self) -> None: ...

    @abstractmethod
    def stop(self) -> None: ...

    def honk(self) -> None:
        print("Beep beep!")


class Car(Vehicle):
    def start(self) -> None:
        print("Car: push button")

    def stop(self) -> None:
        print("Car: brake")


class Bike(Vehicle):
    def start(self) -> None:
        print("Bike: kick start")

    def stop(self) -> None:
        print("Bike: squeeze lever")


try:
    garage: list[Vehicle] = [Car(), Bike()]
    for v in garage:
        v.start()
        v.honk()
        v.stop()
except Exception as e:
    print("Error:", e)

Abstraction in real life — show what it does, hide how it works

A car gives you a steering wheel and pedals, a remote gives you buttons, a coffee machine gives you one start button, and an ATM gives you Withdraw. Engines, circuits, heaters, and bank servers stay hidden. In Python, an ABC with @abstractmethod is the WHAT; the subclass writes the HOW.

Python abstraction infographic with real-life examples: car dashboard vs hidden engine, TV remote vs circuit and IR, coffee machine start vs heating and grinding, ATM withdraw vs bank server, Python ABC Vehicle with abstractmethod start and Car implementing it, plus ABC Protocol and duck typing as ways Python achieves abstraction.
Python abstraction — essential features visible, implementation details hidden
  • You see: a small set of operations — start(), pay(), withdraw().
  • Hidden: how each operation works, written inside subclasses.
  • Tools: ABC + @abstractmethod, Protocol, or duck typing.
  • Benefit: callers use a Vehicle; you can swap Car for Bike without changing them.

Real-life examples

  • You use a small set of controls; complex machinery stays hidden and replaceable.
ObjectWhat you useWhat is hiddenPython idea
CarSteer, accelerate, brakeEngine internalsVehicle ABC
ATMPIN, withdrawBank networkAtm Protocol / ABC
RemotePower, volumeIR codesRemoteControl
PaymentPay buttonGateway APIsPayment.pay()
file objectread/writeOS buffersfile-like Protocol

Abstract classes with abc

  • Subclass ABC (or use metaclass=ABCMeta).
  • Mark unfinished methods with @abstractmethod.
  • Instantiating a class that still has abstract methods raises TypeError.
from abc import ABC, abstractmethod


class Payment(ABC):
    @abstractmethod
    def pay(self, amount: float) -> None: ...


class UpiPayment(Payment):
    def pay(self, amount: float) -> None:
        print(f"Paid {amount} via UPI")


try:
    UpiPayment().pay(99.0)
    Payment()  # incomplete ABC
except TypeError as e:
    print("Error:", e)

Abstract properties and classmethods

  • Combine @property with @abstractmethod, or use @abstractmethod under @classmethod / @staticmethod as documented in abc.
  • Concrete subclasses must implement every abstract member.
from abc import ABC, abstractmethod


class Shape(ABC):
    @property
    @abstractmethod
    def area(self) -> float: ...


class Square(Shape):
    def __init__(self, side: float) -> None:
        self._side = side

    @property
    def area(self) -> float:
        return self._side * self._side


try:
    print(Square(4).area)
except Exception as e:
    print("Error:", e)

Duck typing (informal abstraction)

  • “If it quacks like a duck…” — Python often cares about behaviour, not declared ancestry.
  • Any object with read() can act file-like without inheriting from a File class.
  • Great for flexibility; ABCs/Protocols add clarity and early errors.
class Tape:
    def read(self) -> str:
        return "tape-data"


def load(source) -> str:
    return source.read()


try:
    print(load(Tape()))
    print(load(open(__file__, encoding="utf-8")))
except Exception as e:
    print("Error:", e)

Protocols (structural typing)

  • typing.Protocol describes required methods/attributes without inheritance.
  • isinstance checks work if the Protocol is marked @runtime_checkable.
  • Ideal for “interface-like” contracts in typed Python.
from typing import Protocol, runtime_checkable


@runtime_checkable
class Closable(Protocol):
    def close(self) -> None: ...


class Connection:
    def close(self) -> None:
        print("connection closed")


try:
    c = Connection()
    print(isinstance(c, Closable))
    c.close()
except Exception as e:
    print("Error:", e)

Cannot instantiate incomplete ABCs

  • Partial implementations are useful as bases but not as objects.
  • Always implement every abstract method before creating instances.
from abc import ABC, abstractmethod


class Animal(ABC):
    @abstractmethod
    def speak(self) -> None: ...


class Dog(Animal):
    pass  # forgot speak()


try:
    Dog()
except TypeError as e:
    print("Error:", e)
L2

Advanced — Abstraction

Template method pattern

  • ABC defines the algorithm skeleton; subclasses fill in steps.
  • Keeps shared workflow in one place (brew coffee / tea example).
from abc import ABC, abstractmethod


class Beverage(ABC):
    def prepare(self) -> None:
        self.boil_water()
        self.brew()
        self.pour()

    def boil_water(self) -> None:
        print("Boiling water")

    @abstractmethod
    def brew(self) -> None: ...

    def pour(self) -> None:
        print("Pouring into cup")


class Tea(Beverage):
    def brew(self) -> None:
        print("Steeping tea")


try:
    Tea().prepare()
except Exception as e:
    print("Error:", e)

register virtual subclasses

  • ABC.register(ExistingClass) makes isinstance succeed without editing that class.
  • Used by collections ABCs for built-in types.
from abc import ABC, abstractmethod


class Drawable(ABC):
    @abstractmethod
    def draw(self) -> None: ...


class LegacyIcon:
    def draw(self) -> None:
        print("icon")


try:
    Drawable.register(LegacyIcon)
    print(isinstance(LegacyIcon(), Drawable))
except Exception as e:
    print("Error:", e)

Abstraction vs encapsulation

  • Abstraction: hide complexity behind a small API.
  • Encapsulation: bundle data + methods and control access (_ / properties).
  • They work together: a clean abstract API is often backed by encapsulated state.
IdeaFocusExample
AbstractionWhat operations existPayment.pay()
EncapsulationHow state is protected@property balance
BothStable façadeATM object

ABCs in the standard library

  • collections.abc defines Sequence, Mapping, Iterable, Callable, etc.
  • Implementing abstract methods (or registering) integrates your types with isinstance checks and generic code.

Design tips

  • Keep ABCs small — many narrow Protocols beat one fat base.
  • Prefer dependency on abstractions in libraries; keep concrete classes at the edges.
  • Do not force inheritance when a Protocol or callback suffices.
L3

Tricky Interview Points

Q1) How do you create an abstract class in Python?

Answer Subclass abc.ABC and mark methods with @abstractmethod. Incomplete subclasses cannot be instantiated.

Q2) What happens if you instantiate an ABC with abstract methods left?

Answer TypeError: Can't instantiate abstract class ... with abstract method ...

Q3) Does Python have interfaces?

Answer No separate keyword. Use ABCs, typing.Protocol, or duck typing as interface-like contracts.

Q4) ABC vs Protocol?

Answer ABC is nominal (must inherit or register). Protocol is structural (shape matching). Protocol suits typed duck typing; ABC suits shared implementation + contract.

Q5) What is duck typing?

Answer Choosing objects by behaviour (methods/attributes present) rather than by explicit inheritance.

Q6) Abstraction vs encapsulation?

Answer Abstraction hides complexity behind an API; encapsulation hides and protects internal state. Both support maintainable OOP.

Q7) Can abstract methods have a body?

Answer Yes — the body is ignored for subclasses that must still override, but can document or provide helpers via super in rare patterns.

Q8) What is abc.ABCMeta.register?

Answer Declares an existing class a virtual subclass so isinstance/issubclass succeed without true inheritance.

Q9) Why use template method with ABCs?

Answer The base class owns the algorithm order; subclasses supply only varying steps, avoiding duplication.

Q10) When is duck typing better than an ABC?

Answer Small scripts, stdlib file-like interchange, and when forcing a common base would create artificial coupling.

Q11) Can you have abstract properties?

Answer Yes — stack @property and @abstractmethod (order matters: abstractmethod closest to the function in older docs; property on top is common).

Q12) Name three collections.abc types.

Answer Examples: Sequence, MutableMapping, Iterable, Iterator, Callable, Set.

L4

Simple Programs

Payment gateway ABC

from abc import ABC, abstractmethod


class Payment(ABC):
    @abstractmethod
    def pay(self, amount: float) -> None: ...


class CardPayment(Payment):
    def pay(self, amount: float) -> None:
        print(f"Card charged {amount:.2f}")


class CashPayment(Payment):
    def pay(self, amount: float) -> None:
        print(f"Cash received {amount:.2f}")


def checkout(method: Payment, amount: float) -> None:
    method.pay(amount)


try:
    checkout(CardPayment(), 250)
    checkout(CashPayment(), 99.5)
except Exception as e:
    print("Error:", e)

Shape areas via abstract property

from abc import ABC, abstractmethod
import math


class Shape(ABC):
    @property
    @abstractmethod
    def area(self) -> float: ...


class Circle(Shape):
    def __init__(self, r: float) -> None:
        self.r = r

    @property
    def area(self) -> float:
        return math.pi * self.r * self.r


class Rectangle(Shape):
    def __init__(self, w: float, h: float) -> None:
        self.w, self.h = w, h

    @property
    def area(self) -> float:
        return self.w * self.h


try:
    shapes: list[Shape] = [Circle(2), Rectangle(3, 4)]
    for s in shapes:
        print(type(s).__name__, round(s.area, 2))
except Exception as e:
    print("Error:", e)

Runtime-checkable Protocol

from typing import Protocol, runtime_checkable


@runtime_checkable
class Reader(Protocol):
    def read(self) -> str: ...


class MemoryReader:
    def read(self) -> str:
        return "hello"


def slurp(r: Reader) -> str:
    return r.read()


try:
    print(isinstance(MemoryReader(), Reader))
    print(slurp(MemoryReader()))
except Exception as e:
    print("Error:", e)

Template method — data export

from abc import ABC, abstractmethod


class Exporter(ABC):
    def export(self, rows: list[dict]) -> str:
        header = self.header(rows)
        body = self.body(rows)
        return header + "\n" + body

    @abstractmethod
    def header(self, rows: list[dict]) -> str: ...

    @abstractmethod
    def body(self, rows: list[dict]) -> str: ...


class CsvExporter(Exporter):
    def header(self, rows: list[dict]) -> str:
        return ",".join(rows[0].keys()) if rows else ""

    def body(self, rows: list[dict]) -> str:
        return "\n".join(",".join(str(v) for v in row.values()) for row in rows)


try:
    data = [{"name": "Asha", "score": 90}, {"name": "Ravi", "score": 85}]
    print(CsvExporter().export(data))
except Exception as e:
    print("Error:", e)

Catch incomplete ABC instantiation

from abc import ABC, abstractmethod


class Service(ABC):
    @abstractmethod
    def run(self) -> None: ...


try:
    Service()
except TypeError as e:
    print("Error:", e)
L5

Problem Solving Tricks

  • Import from abc: ABC, abstractmethod, sometimes abstractproperty (legacy).
  • Use @runtime_checkable only on Protocols that are safe to isinstance-check (methods, not complex annotations alone).
  • Keep abstract APIs tiny; push details into concrete classes.
  • collections.abc is the stdlib vocabulary for container contracts.
  • Register virtual subclasses sparingly — it can surprise readers.
  • Duck typing + type hints via Protocol gives flexibility with editor help.
  • Abstract __init__ is uncommon; prefer abstract setup methods.
  • Document required abstract methods in the ABC docstring.
  • Combine concrete helpers and abstract hooks (template method).
  • Fail fast: leave classes abstract until every method is ready.
L6

Practice Programs List

  1. Build Animal ABC with speak; implement Dog and Cat; loop-call speak.
  2. Try instantiating the ABC and catch/print TypeError.
  3. Write a @runtime_checkable Protocol Writable with write(text).
  4. Implement template method prepare() for Coffee and Tea.
  5. Register a legacy class on an ABC and verify isinstance.
  6. Compare encapsulation (_ balance) with an abstract Account API.
  7. Create Shape ABC with abstract perimeter and area.
  8. Refactor a duck-typed function to accept a Protocol parameter.
  9. Use collections.abc.Sequence isinstance checks on a custom class.
  10. Design a Payment ABC with UPI, Card, NetBanking concrete classes.