How to Create Abstract Class in Python: Simple Guide
In Python, you create an abstract class by importing
ABC and abstractmethod from the abc module and then defining a class that inherits from ABC. You mark methods as abstract using the @abstractmethod decorator, which means subclasses must implement these methods.Syntax
To create an abstract class, import ABC and abstractmethod from the abc module. Define a class that inherits from ABC. Use the @abstractmethod decorator to mark methods that must be implemented by subclasses.
- ABC: Base class for defining abstract classes.
- @abstractmethod: Decorator to declare abstract methods.
python
from abc import ABC, abstractmethod class MyAbstractClass(ABC): @abstractmethod def my_method(self): pass
Example
This example shows an abstract class Animal with an abstract method sound. The subclass Dog implements the sound method. Trying to instantiate Animal directly will cause an error.
python
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass class Dog(Animal): def sound(self): return "Woof!" # dog is an instance of Dog dog = Dog() print(dog.sound()) # animal = Animal() # This will raise an error
Output
Woof!
Common Pitfalls
Common mistakes include trying to instantiate an abstract class directly, which raises a TypeError. Also, forgetting to implement all abstract methods in subclasses will cause errors when creating instances.
Always implement every abstract method in subclasses to avoid errors.
python
from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def drive(self): pass # Wrong: subclass does not implement abstract method class Car(Vehicle): pass # car = Car() # Raises TypeError: Can't instantiate abstract class Car with abstract method drive # Correct implementation class Bike(Vehicle): def drive(self): return "Riding the bike" bike = Bike() print(bike.drive())
Output
Riding the bike
Quick Reference
| Concept | Description |
|---|---|
| ABC | Base class to create abstract classes |
| @abstractmethod | Decorator to mark methods that must be implemented |
| Cannot instantiate | Abstract classes cannot be instantiated directly |
| Subclass implementation | Subclasses must implement all abstract methods |
Key Takeaways
Use the abc module's ABC and @abstractmethod to create abstract classes and methods.
Abstract classes cannot be instantiated directly; only subclasses with all abstract methods implemented can be instantiated.
Always implement every abstract method in subclasses to avoid errors.
Abstract classes help define a common interface for subclasses.
Trying to instantiate an abstract class or incomplete subclass raises a TypeError.