Abstraction is one of the four fundamental principles of object-oriented programming (OOP), along with encapsulation, inheritance, and polymorphism. Abstraction allows you to hide the internal details and complexities of a system and expose only the relevant parts. This makes it easier to manage and understand complex systems.
Python provides the abc module to implement abstraction. This module allows you to define abstract base classes and abstract methods.
An abstract class is a class that cannot be instantiated. It typically contains one or more abstract methods.
Example:
from abc import ABC, abstractmethod
# Defining an abstract class
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass # Abstract method
def sleep(self):
return f"{self.__class__.__name__} is sleeping" # Concrete method
# Attempting to create an instance of an abstract class will raise an error
# animal = Animal() # TypeError: Can't instantiate abstract class Animal with abstract methods make_sound
An abstract method is a method declared in an abstract class that must be overridden in any subclass.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
# Subclassing the abstract class and providing an implementation for the abstract method
class Dog(Animal):
def make_sound(self):
return "Woof!"
class Cat(Animal):
def make_sound(self):
return "Meow!"
# Creating instances of the subclasses
dog = Dog()
cat = Cat()
print(dog.make_sound()) # Output: Woof!
print(cat.make_sound()) # Output: Meow!
print(dog.sleep()) # Output: Dog is sleeping
print(cat.sleep()) # Output: Cat is sleeping
Let's consider a more comprehensive example involving different types of vehicles.
Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass
@abstractmethod
def stop_engine(self):
pass
def description(self):
return f"This is a {self.__class__.__name__}"
# Subclass for a car
class Car(Vehicle):
def start_engine(self):
return "Car engine started"
def stop_engine(self):
return "Car engine stopped"
# Subclass for a bike
class Bike(Vehicle):
def start_engine(self):
return "Bike engine started"
def stop_engine(self):
return "Bike engine stopped"
# Creating instances of the subclasses
car = Car()
bike = Bike()
print(car.start_engine()) # Output: Car engine started
print(car.stop_engine()) # Output: Car engine stopped
print(car.description()) # Output: This is a Car
print(bike.start_engine()) # Output: Bike engine started
print(bike.stop_engine()) # Output: Bike engine stopped
print(bike.description()) # Output: This is a Bike