Learn Python
>>> oop_fundamentals.abstraction

Abstraction & Abstract Classes in Python

#concept

Abstraction means exposing only what a user of a class needs to know — the what — while hiding the how behind the scenes. Python formalizes this with abstract base classes, using the abc module: a class marked as abstract can define methods that every subclass must implement, without providing an implementation itself, and Python prevents the abstract class from being instantiated directly.

#how it works
1

Import from the abc module

ABC and abstractmethod provide the tools for building an abstract base class.

2

Inherit from ABC

Marks the class itself as abstract.

3

Decorate a method with @abstractmethod

Requires every subclass to implement it, with no body of its own.

4

The abstract class can’t be instantiated

Attempting it directly raises a TypeError — it exists only to be inherited from.

5

Subclasses must implement every abstract method

Before they themselves can be instantiated.

#example
from abc import ABC, abstractmethod
 
class Shape(ABC):
@abstractmethod
def area(self):
pass
 
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
 
def area(self):
return 3.14 * self.radius ** 2
 
c = Circle(5)
print(c.area())
Output
78.5
1Shape(ABC) marks Shape as an abstract base class, and area() is declared abstract with no real implementation.
2Attempting Shape() directly would raise a TypeError, since Shape is meant only to be inherited from, never instantiated on its own.
3Circle(Shape) provides a real implementation of area(), satisfying the requirement — this makes Circle a valid, instantiable class.
4c.area() runs Circle’s own implementation, calculating the actual area for that specific circle.
#use cases
Defining a required interface that every subclass must follow, like every Shape needing an area() method
Preventing an incomplete or intentionally generic class from being used directly by mistake
Documenting a contract for other developers extending a framework or library
Catching a missing implementation immediately, at class-definition time, rather than as a confusing runtime error later

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.