Python Abstraction
Abstraction is an important concept in object-oriented programming that allows you to create abstract classes and methods. It provides a way to define a common interface for a group of related classes while hiding the implementation details of each class. Abstraction focuses on what an object does rather than how it does it.
In Python, abstraction can be achieved through abstract classes and abstract methods using the abc module (Abstract Base Classes). The abc module provides the ABC class as the base class for creating abstract classes and the abstractmethod decorator to define abstract methods.
Here's an example that demonstrates abstraction in Python:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * (self.radius ** 2)
# Creating objects of the derived classes
rectangle = Rectangle(5, 3)
circle = Circle(7)
# Calling the abstract method on the objects
print(rectangle.calculate_area()) # Output: 15
print(circle.calculate_area()) # Output: 153.86
In the above code, the Shape class is an abstract class with an abstract method calculate_area(). The abstractmethod decorator is used to mark the method as abstract. The abstract method doesn't have any implementation and must be overridden in the derived classes.
The Rectangle and Circle classes are derived from the Shape class. They provide their own implementations of the calculate_area() method according to their specific shapes.
When creating objects of the derived classes (rectangle = Rectangle(5, 3) and circle = Circle(7)), we can call the calculate_area() method on these objects. The actual implementation of the calculate_area() method is determined by the specific derived class.
The key idea behind abstraction is to create a common interface (in this case, the calculate_area() method) that ensures all derived classes provide their own implementation of the method. This allows you to work with objects at a higher level of abstraction, focusing on what the objects can do rather than the details of how they do it.