Python Abstraction
What is Abstraction?
Abstraction is one of the four core principles of Object-Oriented Programming (OOP), along with inheritance, encapsulation, and polymorphism.
Definition:
Abstraction means hiding the internal implementation and showing only the essential features of an object.
In Python, abstraction is typically implemented using abstract classes and abstract methods with the help of the abc
module (abc
stands for Abstract Base Classes).
Why Use Abstraction?
- To simplify complexity.
- To enforce a common interface across different classes.
- To define blueprints for other classes.
Implementing Abstraction with abc
Module
➤ Step-by-Step:
- Import
ABC
andabstractmethod
fromabc
module. - Create a class that inherits from
ABC
. - Use
@abstractmethod
to define methods that must be implemented in subclasses.
Example: Abstract Class in Python
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
class Car(Vehicle):
def start_engine(self):
print("Car engine started.")
class Bike(Vehicle):
def start_engine(self):
print("Bike engine started.")
Usage:
c = Car()
c.start_engine()
b = Bike()
b.start_engine()
Output:
Car engine started.
Bike engine started.
Attempt to Instantiate Abstract Class
v = Vehicle()
Output (Error):
TypeError: Can't instantiate abstract class Vehicle with abstract methods start_engine
Explanation:
You cannot create an object of an abstract class directly. Only its subclasses that implement all abstract methods can be instantiated.
Example: Abstract Class with Multiple Abstract Methods
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
r = Rectangle(4, 5)
print("Area:", r.area())
print("Perimeter:", r.perimeter())
Output:
Area: 20
Perimeter: 18
Key Takeaways
Feature | Description |
---|---|
Abstract Class | Class that cannot be instantiated |
Abstract Method | Method that must be implemented in a subclass |
@abstractmethod | Decorator to declare an abstract method |
ABC | Base class for all abstract classes |
Benefit | Forces subclass to follow a structure (contract) |