MyInternships.in

Python OOP

Python Abstraction

Abstraction means hiding implementation details and exposing only what is necessary, so users of a class focus on what it does rather than how it works.


What Abstraction Solves

Sometimes you want to guarantee that every subclass implements certain methods, without providing a default implementation yourself. Python's abc module (Abstract Base Classes) lets you define such a required interface.

An abstract base class
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

A class that inherits from ABC and has at least one method decorated with @abstractmethod becomes an abstract class. You cannot create objects directly from it.

Trying to instantiate the abstract class fails
Python
s = Shape()
Output
Output
TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeter

Implementing the Interface

Any child class must override every abstract method, or it too remains abstract and cannot be instantiated. This guarantees a consistent set of methods across all shapes.

A concrete subclass
Python
class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h

    def perimeter(self):
        return 2 * (self.w + self.h)

r = Rectangle(4, 5)
print(r.area(), r.perimeter())
Output
Output
20 18
💡

Use abstraction when you are designing a family of related classes (shapes, payment methods, file readers) and want to force every subclass to provide certain behaviour.

ℹ️

Abstraction and encapsulation are related but different: encapsulation hides data, while abstraction hides implementation complexity behind a simple, required interface.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships