Interview Questions, Answers and Tutorials

Abstract classes and abstract methods

Abstract classes and abstract methods

Hey there, future programmer! Today, we’re going to learn about something super cool in Python called abstract classes and abstract methods. Don’t worry, I’ll explain everything step by step. Think of this as a fun story with code and practice questions at the end!

What Are Abstract Classes?

Imagine you’re in charge of building different types of vehicles. You know all vehicles need some common parts like wheels and engines, but each vehicle (like a car, bike, or truck) is a bit different. Instead of building each vehicle from scratch, you create a blueprint called a “Vehicle.” This blueprint has some general instructions, but it doesn’t provide all the details.

In Python, this blueprint is called an abstract class. An abstract class is like a plan that outlines how some things should work but leaves the details to be filled in by other classes. You can’t use an abstract class directly to create objects; you need to use it as a guide to create other, more specific classes.

What Are Abstract Methods?

In our vehicle blueprint, we might say that every vehicle must have a way to start and stop. However, we don’t explain exactly how to start or stop the vehicle. These are abstract methods. An abstract method is a method declared in an abstract class that doesn’t have any code in it yet. It’s like saying, “We need this function, but we’ll figure out the details later.”

How to Use Abstract Classes and Methods in Python

Let’s see how we can create and use abstract classes and methods with some Python code.

First, we need to import a special module to help us create abstract classes.

from abc import ABC, abstractmethod

Here, ‘ABCstands for Abstract Base Class.

Creating an Abstract Class

Let’s create an abstract class called ‘Vehicle‘:

from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod  # This is a decorator indicating an abstract method
    def start(self):
        pass

    @abstractmethod
    def stop(self):
        pass

In this code:

  • Vehicleis our abstract class.
  • startand stop are abstract methods, which means they don’t have any code yet.

Creating a Subclass

Now, let’s create a specific vehicle, like a 'Car‘, which follows the ‘Vehicleblueprint.

class Car(Vehicle):
    def start(self):
        print("Car is starting with a key.")

    def stop(self):
        print("Car is stopping by pressing the brake.")

In this code:

  • Caris a subclass of ‘Vehicle‘.
  • We provided the details for how a car starts and stops.

Example in Action

Let’s put it all together and see how it works:

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 is starting with a key.")

    def stop(self):
        print("Car is stopping by pressing the brake.")

# Trying to create an object of Vehicle directly will give an error
# vehicle = Vehicle()  # This will cause an error

# Creating an object of Car
my_car = Car()
my_car.start()  # Output: Car is starting with a key.
my_car.stop()   # Output: Car is stopping by pressing the brake.





Practice Questions

Here are some practice questions for you to try:

Question 1

Create an abstract class called ‘Animal' with abstract methods ‘make_sound‘ and ‘move‘. Then, create a subclass called ‘Dogthat provides specific implementations for these methods.

Question 2

Create an abstract class called ‘Shapewith an abstract method ‘area‘. Then, create two subclasses: ‘Circleand ‘Square', which implements the ‘areamethod for a circle and a square, respectively.

Solutions

Solution 1

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

    @abstractmethod
    def move(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Bark!")

    def move(self):
        print("The dog runs.")

# Creating an object of Dog
my_dog = Dog()
my_dog.make_sound()  # Output: Bark!
my_dog.move()        # Output: The dog runs.





Solution 2

from abc import ABC, abstractmethod
import math

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

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

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

class Square(Shape):
    def __init__(self, side):
        self.side = side

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

# Creating objects of Circle and Square
my_circle = Circle(5)
my_square = Square(4)

print(f"Circle area: {my_circle.area()}")  # Output: Circle area: 78.53981633974483
print(f"Square area: {my_square.area()}")  # Output: Square area: 16





Abstract classes and methods are powerful tools in Python that help you create blueprints for other classes. They ensure that certain methods are always implemented in subclasses, making your code more organized and easier to manage. Keep practicing with different examples, and you’ll become a pro in no time!

Happy coding!