Python Abstraction
Table of Contents
In the last lesson, we learned about Python Encapsulation. After learning about encapsulation, let us learn about abstraction in Python. Abstraction means hiding complex details and showing only what is needed.
In this tutorial, we will learn what abstraction is, how to use it, and why it is useful.
What Is Abstraction in Python?
Abstraction is the practice of hiding complex details from the user. We show only the essential features.
Think of it like driving a car. We use the steering wheel, pedals, and gear stick. We do not need to know how the engine works. The complex details are hidden.
In Python, abstraction means creating a simple interface for complex code.
Why Do We Need Abstraction in Python?
Abstraction makes our code easier to use. Users do not need to understand all the details. They just use the simple interface.
It also makes our code easier to change. We can change the internal details without affecting the outside code.
How to Achieve Abstraction in Python
Python does not have abstract classes built in like some languages. But we can use the abc module to create them.
The abc module stands for βAbstract Base Classes.β
from abc import ABC, abstractmethod
class Shape(ABC): @abstractmethod def area(self): pass
class Circle(Shape): def __init__(self, radius): self.radius = radius
def area(self): return 3.14 * self.radius ** 2
circle = Circle(5)print(circle.area())Output
78.5Here, Shape is an abstract class. It has an abstract method area. We cannot create an object of Shape. We must create a subclass and implement the abstract method.
Abstract Methods in Python
An abstract method is a method that has no implementation in the abstract class. Subclasses must implement it.
from abc import ABC, abstractmethod
class Animal(ABC): @abstractmethod def speak(self): pass
class Dog(Animal): def speak(self): print("Woof!")
class Cat(Animal): def speak(self): print("Meow!")
dog = Dog()cat = Cat()
dog.speak()cat.speak()Output
Woof!Meow!If we try to create an object of Animal, we get an error.
animal = Animal()Output
TypeError: Can't instantiate abstract class Animal with abstract method speakThat is abstraction. We force subclasses to implement the method.
Abstract Properties in Python
We can also have abstract properties.
from abc import ABC, abstractmethod
class Vehicle(ABC): @property @abstractmethod def wheels(self): pass
class Car(Vehicle): @property def wheels(self): return 4
class Bike(Vehicle): @property def wheels(self): return 2
car = Car()bike = Bike()
print(car.wheels)print(bike.wheels)Output
42That is a clean way to use abstraction with properties.
A Real-Life Example β Payment System
from abc import ABC, abstractmethod
class Payment(ABC): @abstractmethod def pay(self, amount): pass
@abstractmethod def refund(self, amount): pass
class CreditCard(Payment): def pay(self, amount): print(f"Paid {amount} using credit card")
def refund(self, amount): print(f"Refunded {amount} to credit card")
class PayPal(Payment): def pay(self, amount): print(f"Paid {amount} using PayPal")
def refund(self, amount): print(f"Refunded {amount} to PayPal")
payments = [CreditCard(), PayPal()]
for payment in payments: payment.pay(100) payment.refund(50)Output
Paid 100 using credit cardRefunded 50 to credit cardPaid 100 using PayPalRefunded 50 to PayPalThat is abstraction. The Payment class defines the interface. The subclasses implement it.
When to Use Abstraction in Python
Use abstraction when:
- We want to define a common interface for a group of classes
- We want to force subclasses to implement certain methods
- We want to hide complex details from the user
Do not use abstraction when:
- The class does not need a common interface
- The methods are not shared across subclasses
Common Mistakes with Abstraction in Python
Mistake 1: Forgetting to import ABC and abstractmethod
class Shape(ABC): @abstractmethod def area(self): passThis gives an error if we did not import.
Fix:
from abc import ABC, abstractmethodMistake 2: Forgetting to implement all abstract methods
class Shape(ABC): @abstractmethod def area(self): pass
@abstractmethod def perimeter(self): pass
class Circle(Shape): def area(self): return 3.14 * 5 ** 2This gives an error. Because perimeter is not implemented.
Fix: Implement all abstract methods.
class Circle(Shape): def area(self): return 3.14 * 5 ** 2
def perimeter(self): return 2 * 3.14 * 5Mistake 3: Trying to create an object of an abstract class
shape = Shape()This gives an error. Abstract classes cannot be instantiated.
Fix: Create a subclass and implement the methods.
Next, we will learn about Python Magic Methods and make objects work with built-in Python operations.