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.
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 (
abcmodule), 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.
- 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 swapCarforBikewithout changing them.
Real-life examples
- You use a small set of controls; complex machinery stays hidden and replaceable.
| Object | What you use | What is hidden | Python idea |
|---|---|---|---|
| Car | Steer, accelerate, brake | Engine internals | Vehicle ABC |
| ATM | PIN, withdraw | Bank network | Atm Protocol / ABC |
| Remote | Power, volume | IR codes | RemoteControl |
| Payment | Pay button | Gateway APIs | Payment.pay() |
| file object | read/write | OS buffers | file-like Protocol |
Abstract classes with abc
- Subclass
ABC(or usemetaclass=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
@propertywith@abstractmethod, or use@abstractmethodunder@classmethod/@staticmethodas documented inabc. - 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.Protocoldescribes required methods/attributes without inheritance.isinstancechecks 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) 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)makesisinstancesucceed 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.
| Idea | Focus | Example |
|---|---|---|
| Abstraction | What operations exist | Payment.pay() |
| Encapsulation | How state is protected | @property balance |
| Both | Stable façade | ATM object |
ABCs in the standard library
collections.abcdefinesSequence,Mapping,Iterable,Callable, etc.- Implementing abstract methods (or registering) integrates your types with
isinstancechecks 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.
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.
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) Problem Solving Tricks
- Import from
abc:ABC,abstractmethod, sometimesabstractproperty(legacy). - Use
@runtime_checkableonly on Protocols that are safe to isinstance-check (methods, not complex annotations alone). - Keep abstract APIs tiny; push details into concrete classes.
collections.abcis 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.
Practice Programs List
- Build
AnimalABC withspeak; implement Dog and Cat; loop-call speak. - Try instantiating the ABC and catch/print TypeError.
- Write a
@runtime_checkableProtocolWritablewithwrite(text). - Implement template method
prepare()for Coffee and Tea. - Register a legacy class on an ABC and verify isinstance.
- Compare encapsulation (
_balance) with an abstractAccountAPI. - Create Shape ABC with abstract
perimeterandarea. - Refactor a duck-typed function to accept a Protocol parameter.
- Use
collections.abc.Sequenceisinstance checks on a custom class. - Design a Payment ABC with UPI, Card, NetBanking concrete classes.