Introduction
Abstraction is a fundamental concept in object-oriented programming (OOP) that focuses on hiding the implementation details and showing only the essential features of an object. This allows the user to interact with the object at a higher level without needing to understand the complexity of its inner workings. In Python, abstraction is typically implemented using abstract classes and abstract methods, which are defined using the abc
module.
An abstract class is a class that cannot be instantiated on its own and serves as a blueprint for other classes. An abstract method is a method that is declared but contains no implementation. Subclasses that inherit from an abstract class must provide concrete implementations for the abstract methods.
This tutorial will guide you through creating a Python program that demonstrates abstraction by defining an abstract class and implementing its abstract methods in subclasses.
Example:
- Abstract Class:
Vehicle
- Abstract Method:
start()
- Subclasses:
Car
,Bike
- Program Output:
The car starts with a key. The bike starts with a button.
Problem Statement
Create a Python program that:
- Defines an abstract class named
Vehicle
with an abstract methodstart
. - Defines two subclasses
Car
andBike
that inherit fromVehicle
and implement thestart
method. - Creates objects of
Car
andBike
classes and calls thestart
method to demonstrate abstraction.
Solution Steps
- Import the
abc
Module: Import theABC
andabstractmethod
from theabc
module to define abstract classes and methods. - Define the Abstract Class: Use the
class
keyword to define an abstract class namedVehicle
. - Add an Abstract Method: Define an abstract method named
start
within theVehicle
class. - Define Subclasses: Use the
class
keyword to define subclassesCar
andBike
that inherit fromVehicle
. - Implement the Abstract Method: Provide concrete implementations of the
start
method in bothCar
andBike
classes. - Create Objects and Demonstrate Abstraction: Instantiate objects of
Car
andBike
classes and call thestart
method on them.
Python Program
# Python Program to Implement Abstraction
# Author: https://www.rameshfadatare.com/
# Step 1: Import the abc Module
from abc import ABC, abstractmethod
# Step 2: Define the Abstract Class
class Vehicle(ABC):
# Step 3: Add an Abstract Method
@abstractmethod
def start(self):
pass
# Step 4: Define Subclass Car
class Car(Vehicle):
# Step 5: Implement the Abstract Method
def start(self):
print("The car starts with a key.")
# Step 4: Define Subclass Bike
class Bike(Vehicle):
# Step 5: Implement the Abstract Method
def start(self):
print("The bike starts with a button.")
# Step 6: Create Objects and Demonstrate Abstraction
my_car = Car()
my_bike = Bike()
my_car.start() # Output: The car starts with a key.
my_bike.start() # Output: The bike starts with a button.
Explanation
Step 1: Import the abc Module
- The
abc
module in Python provides tools for defining abstract base classes. TheABC
class is used as the base class for abstract classes, and theabstractmethod
decorator is used to declare abstract methods.
Step 2: Define the Abstract Class
- The
Vehicle
class is defined as an abstract class by inheriting fromABC
. This class cannot be instantiated and serves as a blueprint for other classes.
Step 3: Add an Abstract Method
- The
start
method is declared as an abstract method using the@abstractmethod
decorator. This method does not contain any implementation and must be overridden in any subclass that inherits fromVehicle
.
Step 4: Define Subclasses
- The
Car
andBike
classes are defined as subclasses ofVehicle
. These classes must provide concrete implementations of thestart
method.
Step 5: Implement the Abstract Method
- The
start
method is implemented in bothCar
andBike
classes. TheCar
class provides a specific implementation where the car starts with a key, and theBike
class provides a different implementation where the bike starts with a button.
Step 6: Create Objects and Demonstrate Abstraction
- Objects
my_car
andmy_bike
are created from theCar
andBike
classes, respectively. Thestart
method is called on both objects to demonstrate how the abstract method is implemented differently in each subclass.
Output Example
Example Output:
The car starts with a key.
The bike starts with a button.
Additional Examples
Example 1: Abstract Class with Multiple Abstract Methods
# Define a more complex abstract class
class Appliance(ABC):
@abstractmethod
def turn_on(self):
pass
@abstractmethod
def turn_off(self):
pass
# Implementing the abstract class in a subclass
class WashingMachine(Appliance):
def turn_on(self):
print("Washing machine is now ON.")
def turn_off(self):
print("Washing machine is now OFF.")
# Create an object of WashingMachine
wm = WashingMachine()
wm.turn_on()
wm.turn_off()
Output:
Washing machine is now ON.
Washing machine is now OFF.
Example 2: Abstract Class with Concrete Methods
# Abstract class with a concrete method
class Animal(ABC):
@abstractmethod
def sound(self):
pass
def breathe(self):
print("Animal is breathing")
# Subclass that implements the abstract method
class Dog(Animal):
def sound(self):
print("The dog barks")
# Create an object of Dog and demonstrate both methods
dog = Dog()
dog.sound() # Abstract method implementation
dog.breathe() # Concrete method from abstract class
Output:
The dog barks
Animal is breathing
Example 3: Abstract Class with Initialization
# Abstract class with constructor
class Shape(ABC):
def __init__(self, color):
self.color = color
@abstractmethod
def area(self):
pass
# Subclass that implements the abstract method
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Create an object of Circle and demonstrate the area calculation
circle = Circle("Red", 5)
print(f"Circle area: {circle.area()}")
Output:
Circle area: 78.5
Conclusion
This Python program demonstrates how to implement abstraction, a core concept in object-oriented programming that hides the complexity of implementation details while exposing only the essential features. Abstraction is typically achieved using abstract classes and methods, which enforce a contract for subclasses to implement specific functionality. Understanding and applying abstraction is essential for designing clean, maintainable, and scalable code in Python.