Abstraction in Python
Learn how abstraction hides unnecessary implementation details and shows only the important functionality.
What is Abstraction?
Abstraction is an important concept of Object-Oriented Programming.
Abstraction means hiding unnecessary implementation details and showing only the important functionality to the user.
Example 🌍📩
Think about using an ATM.
You select: Withdraw Money.
You do not need to know how the bank server checks your account, validates the transaction and processes the withdrawal internally.
You only use the required functionality.
What User Sees
Insert card
Enter PIN
Select amount
Receive money
What System Hides
Account validation
Server processing
Transaction verification
Database operations
Abstraction Diagram
The user sees only the required functionality while the internal implementation remains hidden.
User
Uses required functionality
Visible Interface
Methods or operations available to the user
Hidden Implementation
Internal logic and processing remains hidden
Result
User gets the required output without knowing the internal implementation.
Why Do We Use Abstraction?
- Hides unnecessary implementation details.
- Shows only important functionality.
- Makes large programs easier to understand.
- Reduces complexity.
- Makes code easier to maintain.
Simple Python Example
First, let's understand the basic idea without using the abstract class module.
class Car:
def start(self):
print("Car started")
car1 = Car()
car1.start()
Output:
Car started
The user only calls start().
The internal process of starting the car can remain
hidden inside the class.
Abstract Class
Python provides the abc module for creating
abstract classes.
We commonly use:
-
ABC -
abstractmethod
from abc import ABC, @abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
Here, Animal is an abstract class and
sound() is an abstract method.
What is an Abstract Method?
An abstract method is a method that is declared in the parent abstract class but its implementation is provided by the child class.
from abc import ABC, @abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Dog barks")
The parent class says that every animal should have
a sound() method.
The child class decides how that method will work.
Complete Abstraction Example
from abc import ABC, @abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Dog barks")
class Cat(Animal):
def sound(self):
print("Cat meows")
dog1 = Dog()
cat1 = Cat()
dog1.sound()
cat1.sound()
Output:
Dog barks
Cat meows
Here the parent class provides the common structure, while each child class provides its own implementation.
Can We Create an Object of an Abstract Class?
No. We cannot normally create an object directly from an abstract class while it still contains unimplemented abstract methods.
from abc import ABC, @abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
animal1 = Animal()
This produces an error because
Animal contains an abstract method that
has not been implemented.
We should create objects from concrete child classes that implement all required abstract methods.
Child Class Must Implement Abstract Methods
If a child class does not implement an abstract method, that child class also remains abstract.
from abc import ABC, @abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
car1 = Car()
car1.start()
Output:
Car started
Multiple Abstract Methods
An abstract class can contain more than one abstract method.
from abc import ABC, @abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
car1 = Car()
car1.start()
car1.stop()
Output:
Car started
Car stopped
The child class must implement both abstract methods.
Example: Payment System 🖥️🔓
Imagine an application that supports different payment methods.
Every payment method should provide a
pay() operation, but the implementation
can be different.
from abc import ABC, @abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
pass
class UPI(Payment):
def pay(self, amount):
print("Paid", amount, "using UPI")
class Card(Payment):
def pay(self, amount):
print("Paid", amount, "using Card")
upi1 = UPI()
card1 = Card()
upi1.pay(500)
card1.pay(1000)
Output:
Paid 500 using UPI
Paid 1000 using Card
The common rule is pay(), while each
payment class provides its own implementation.
Abstraction and Inheritance
Abstraction is commonly implemented using inheritance.
The abstract parent class defines the required methods, and the child class provides the actual implementation.
Abstract Parent
|
v
Child Class
|
v
Actual Implementation
Abstraction vs Encapsulation
| Abstraction | Encapsulation |
|---|---|
| Hides unnecessary implementation details. | Controls access to data and methods. |
| Focuses on what an object does. | Focuses on how data is protected. |
| Commonly uses abstract classes and methods. | Commonly uses access conventions, private attributes and controlled methods. |
Benefits of Abstraction
- Hides unnecessary details.
- Reduces program complexity.
- Makes code easier to understand.
- Creates common rules for child classes.
- Makes large applications easier to maintain.
Common Mistakes
-
Forgetting to inherit from
ABC. -
Forgetting the
@abstractmethoddecorator in a code example. - Trying to create an object of an incomplete abstract class.
- Forgetting to implement all abstract methods in the child class.
Practice Programs
-
Create an abstract
Animalclass with an abstractsound()method. -
Create
DogandCatclasses that implementsound(). -
Create an abstract
Vehicleclass withstart()andstop(). -
Create
CarandBikeclasses. -
Create a payment system using an abstract
Paymentclass.
Summary
Abstraction means hiding unnecessary implementation
details and showing only the required functionality.
Python supports abstraction using the
abc module, abstract classes and
abstract methods. An abstract class defines common
rules, while child classes provide the actual
implementation.