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.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
passA 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.
s = Shape()TypeError: Can't instantiate abstract class Shape with abstract methods area, perimeterImplementing 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.
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())20 18Use 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.
