Abstract Classes in Python

Updated: April 2nd, 2023, 01:17:18 IST
Published: April 1st, 2023
Abstract Classes in Python
Title: Abstract Classes in Python

In Python, an abstract class is a class that cannot be instantiated on its own and is intended to be subclassed by other classes. An abstract class can contain one or more abstract methods, which are methods that have no implementation in the abstract class but must be implemented by its subclasses.

Abstract classes are defined using the abc module in Python, which provides the ABC class and the abstractmethod decorator. The ABC class is used as the base class for abstract classes, and the abstractmethod decorator is used to mark a method as an abstract method.

An abstract class can be used to define a common interface for a group of subclasses, without specifying the implementation details. This allows for greater flexibility and modularity in the code, as well as better organization and maintainability.

An example of an abstract class in Python using the abc module:

from abc import ABC, abstractmethod

class Shape(ABC):

    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

In this example, we define an abstract class called Shape with two abstract methods: area() and perimeter(). Any class that subclasses Shape must provide implementations for these two methods.

Example

from abc import ABC, abstractmethod

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

class Dog(Animal):
    def sound(self):
        print("Bark")

class Cat(Animal):
    def sound(self):
        print("Meow")

In this example, we define an abstract class Animal with an abstract method sound. This means that any class that inherits from Animal must implement a sound method, but we cannot directly create an instance of Animal.

We then define two concrete subclasses of Animal, Dog and Cat. These subclasses implement the sound method with their own specific sound.

Here's an example of how we can use these classes:

my_dog = Dog()
my_cat = Cat()

my_dog.sound() # Output: Bark
my_cat.sound() # Output: Meow

In this example, we create instances of Dog and Cat, and call their sound methods to hear their specific sounds. The output will show that the dog barks and the cat meows.