Interview Questions, Answers and Tutorials

Implementing abstract classes

Implementing abstract classes

Hey there! Today, we’re going to learn about abstract classes in Python. Imagine you’re playing with Legos, and you have different types of Lego blocks: some are square, some are round, and some are triangular. An abstract class is like a blueprint for a Lego block, but you can’t build anything with just the blueprint. You need to create specific blocks based on that blueprint.

An abstract class in Python is a class that cannot be instantiated (you can’t create an object directly from it). It is meant to be a base class that other classes inherit from and provide implementations for its methods.

Why Use Abstract Classes?

  1. Consistency: They ensure that certain methods are implemented in all subclasses.
  2. Design: They provide a clear structure for your code, making it easier to understand and maintain.

Creating Abstract Classes in Python

In Python, we use the ‘abcmodule to create abstract classes. The ‘abcmodule stands for “Abstract Base Classes.” Let’s see how to do this step by step.

  1. Import the abc Module:
from abc import ABC, abstractmethod

  1. Define an Abstract Class:
class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

Here, ‘Animalis an abstract class with an abstract method ‘sound‘. The ‘@abstractmethod‘ decorator tells Python that ‘soundis an abstract method and must be implemented by any subclass of ‘Animal'.

  1. Create Subclasses:
class Dog(Animal):
    def sound(self):
        return "Woof!"

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

Now, ‘Dogand ‘Cat' are subclasses of ‘Animal‘, and they provide their own implementation of the ‘soundmethod.

Putting It All Together

Let’s put everything together in a complete example:

from abc import ABC, abstractmethod

# Abstract class
class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

# Subclass implementing the abstract method
class Dog(Animal):
    def sound(self):
        return "Woof!"

# Another subclass implementing the abstract method
class Cat(Animal):
    def sound(self):
        return "Meow!"

# Create instances of the subclasses
dog = Dog()
cat = Cat()

# Print the sounds
print(dog.sound())  # Output: Woof!
print(cat.sound())  # Output: Meow!

Practice Questions

Now it’s your turn to practice!

  1. Question 1: Create an Abstract Class Create an abstract class called ‘Shapewith an abstract method ‘area‘. Then, create two subclasses ‘Circleand ‘Squarethat implement the ‘area‘ method.
  2. Question 2: Implement and Instantiate Implement the ‘Shapeclass with ‘Circleand ‘Squaresubclasses. Create instances of ‘Circlewith radius 3 and ‘Squarewith side 4, and print their areas.

Solutions to Practice Questions

  1. Solution 1: Create an Abstract Class

from abc import ABC, abstractmethod

# Abstract class
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass





  1. Solution 2: Implement and Instantiate

from abc import ABC, abstractmethod
import math

# Abstract class
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

# Subclass implementing the abstract method for Circle
class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * (self.radius ** 2)

# Subclass implementing the abstract method for Square
class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

# Create instances of the subclasses
circle = Circle(3)
square = Square(4)

# Print the areas
print(circle.area())  # Output: 28.274333882308138
print(square.area())  # Output: 16




In this solution, we created an 'Shape' abstract class with a ‘areamethod. Then, we implemented ‘Circle' and ‘Squaresubclasses provided their own ‘area’ method implementations and printed the areas of instances.

That’s it! Now you know how to create and use abstract classes in Python. Happy coding!