Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Python Intermediate - Abstraction

Implementing abstraction in Python

Abstraction is one of the fundamental principles of Object-Oriented Programming (OOP). It allows you to hide the complex implementation details and expose only the necessary parts. Abstraction is achieved through abstract classes and interfaces, which define a blueprint for other classes without providing the full implementation. This tutorial explores how to implement abstraction in Python.

Key Points:

  • Abstraction hides the complex implementation details and exposes only the necessary parts.
  • Abstract classes cannot be instantiated and are meant to be subclassed.
  • Abstract methods are declared in the abstract class and must be implemented in the subclasses.
  • The abc module in Python provides tools for defining abstract classes and methods.

Abstract Classes

Abstract classes are classes that cannot be instantiated and are meant to be subclassed. They can contain abstract methods that must be implemented by the subclasses:


from abc import ABC, abstractmethod

# Example of an abstract class
class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

    def sleep(self):
        print("Sleeping...")

# Subclass of Animal
class Dog(Animal):
    def sound(self):
        return "Woof!"

# Subclass of Animal
class Cat(Animal):
    def sound(self):
        return "Meow!"

# Creating objects of Dog and Cat classes
dog = Dog()
cat = Cat()
print(dog.sound())  # Output: Woof!
print(cat.sound())  # Output: Meow!
dog.sleep()  # Output: Sleeping...
cat.sleep()  # Output: Sleeping...
            

In this example, the Animal class is an abstract class with an abstract method sound. The Dog and Cat classes subclass Animal and implement the sound method. The sleep method is a concrete method in the abstract class that can be used by the subclasses.

Abstract Methods

Abstract methods are methods declared in an abstract class that do not have an implementation. Subclasses must implement these methods:


from abc import ABC, abstractmethod

# Example of an abstract class with an abstract method
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Subclass of Shape
class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def area(self):
        return self.width * self.height

# Subclass of Shape
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius * self.radius

# Creating objects of Rectangle and Circle classes
rect = Rectangle(3, 4)
circle = Circle(5)
print(rect.area())  # Output: 12
print(circle.area())  # Output: 78.5
            

In this example, the Shape class is an abstract class with an abstract method area. The Rectangle and Circle classes subclass Shape and implement the area method.

Concrete Methods in Abstract Classes

Abstract classes can also have concrete methods with an implementation. These methods can be used by the subclasses:


from abc import ABC, abstractmethod

# Example of an abstract class with a concrete method
class Vehicle(ABC):
    @abstractmethod
    def start(self):
        pass
    
    def stop(self):
        print("Vehicle stopped")

# Subclass of Vehicle
class Car(Vehicle):
    def start(self):
        print("Car started")

# Subclass of Vehicle
class Bike(Vehicle):
    def start(self):
        print("Bike started")

# Creating objects of Car and Bike classes
car = Car()
bike = Bike()
car.start()  # Output: Car started
bike.start()  # Output: Bike started
car.stop()  # Output: Vehicle stopped
bike.stop()  # Output: Vehicle stopped
            

In this example, the Vehicle class is an abstract class with an abstract method start and a concrete method stop. The Car and Bike classes subclass Vehicle and implement the start method. The stop method is used by the subclasses.

Advantages of Abstraction

Abstraction provides several advantages, including:

  • Simplifies code by hiding complex implementation details.
  • Promotes code reuse through the use of abstract classes and methods.
  • Enhances maintainability by defining clear interfaces for subclasses.
  • Encourages modular design by separating the interface from the implementation.

Summary

In this tutorial, you learned about abstraction in Python, including abstract classes, abstract methods, concrete methods in abstract classes, and the advantages of abstraction. Abstraction hides complex implementation details and exposes only the necessary parts, promoting code reuse, maintainability, and modular design. Understanding abstraction is essential for effective object-oriented programming in Python.