What is Abstract Class in Python: Simple Explanation and Example
abstract class in Python is a class that cannot be instantiated directly and is designed to be a blueprint for other classes. It can define methods that must be created in any subclass, ensuring a consistent interface.How It Works
Think of an abstract class as a blueprint for a house. You cannot live in the blueprint itself, but it tells builders exactly what rooms and features the house must have. Similarly, an abstract class in Python defines methods that subclasses must implement, but you cannot create an object from the abstract class alone.
Python uses the abc module to create abstract classes. When a class inherits from an abstract class, it must provide its own versions of the abstract methods. This ensures that all subclasses follow the same rules, like a contract.
Example
This example shows an abstract class Animal with an abstract method make_sound. The subclasses Dog and Cat implement this method differently.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): return "Woof!" class Cat(Animal): def make_sound(self): return "Meow!" # Trying to create an Animal object will cause an error # animal = Animal() # This would raise TypeError dog = Dog() cat = Cat() print(dog.make_sound()) print(cat.make_sound())
When to Use
Use abstract classes when you want to define a common interface for a group of related classes but don't want to create objects from the base class itself. This is useful in large projects where many classes share similar behavior but implement details differently.
For example, in a game, you might have an abstract class Character with methods like move and attack. Different characters like Wizard and Warrior will implement these methods in their own way.
Key Points
- An abstract class cannot be instantiated directly.
- It defines abstract methods that subclasses must implement.
- It helps enforce a consistent interface across different classes.
- Python uses the
abcmodule to create abstract classes.