0
0
PythonConceptBeginner · 3 min read

What is Abstract Class in Python: Simple Explanation and Example

An 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.

python
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())
Output
Woof! Meow!
🎯

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 abc module to create abstract classes.

Key Takeaways

Abstract classes define methods that subclasses must implement but cannot be instantiated themselves.
Use abstract classes to enforce a consistent interface across related classes.
Python's abc module provides tools to create abstract classes and methods.
Trying to create an object from an abstract class raises a TypeError.
Abstract classes are useful in large projects to organize code and ensure consistency.