Abstraction
Abstraction is the principle of hiding complex implementation details and exposing only what is necessary for outside users. It lets you work with an objec...
Abstraction in Python: Hiding Complexity Behind Simple Interfaces
Abstraction is the principle of hiding complex implementation details and exposing only what is necessary for outside users. It lets you work with an object at a high level without worrying about how it achieves its results internally. A good abstraction simplifies the mental model required to use a system.
In Python, abstraction is often implemented through abstract classes. An abstract class is a class that cannot be instantiated on its own and is designed to be subclassed. It can define abstract methods, which are methods that must be overridden in any concrete subclass. Python provides this through the abc module.
from abc import ABC, abstractmethod
class Shape(ABC): @abstractmethod def area(self): pass
@abstractmethod def perimeter(self): pass
class Circle(Shape): def __init__(self, radius): self.radius = radius
def area(self): return 3.14159 * self.radius ** 2
def perimeter(self): return 2 * 3.14159 * self.radius
c = Circle(5) print(c.area()) # 78.53975 print(c.perimeter()) # 31.4159
If you try to instantiate Shape directly, Python raises a TypeError. This enforces a contract: any class that inherits from Shape must implement both area and perimeter.
Abstraction also happens at a more informal level through well-named functions and classes. When you call a function called send_email, you do not need to know how it connects to the SMTP server. The name and parameters tell you everything you need to use it. This kind of abstraction through naming is just as important as formal abstract classes.
The goal of abstraction is to reduce complexity for the caller. Good abstractions make code easier to use correctly and harder to use incorrectly. They also make it easier to swap out implementations without changing the code that uses them.
Interview tip: Explain that Python's abc module provides formal support for abstraction but that Python also uses informal abstraction through conventions and naming. Mention that @abstractmethod prevents incomplete subclasses from being instantiated, which is a common safety mechanism in large codebases.