Abstract Classes
Abstract classes are classes that cannot be instantiated directly. They serve as base classes for other classes, defining a common interface that subclasses must implement.
Creating Abstract Classes:
To create an abstract class in Python, you use the abc module and the @abstractmethod decorator:
Python
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
Key Points:
- Abstract classes are defined using the ABC class from the abc module.
- The @abstractmethod decorator marks methods as abstract.
- Abstract methods must be implemented in subclasses.
- You cannot create instances of abstract classes directly.
Example:
Python
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
# Trying to create an instance of the abstract class will raise an error:
# animal = Animal() # TypeError: Can't instantiate abstract class Animal with abstract method make_sound
Benefits of Abstract Classes:
- Enforce common interface: Ensure that subclasses implement required methods.
- Promote code reusability: Provide a base class for derived classes.
- Improve code organization: Define a clear structure for related classes.
Cautions:
- Abstract classes cannot be instantiated directly.
- All abstract methods must be implemented in subclasses.
- Overusing abstract classes can make code more complex.
By understanding abstract classes, you can create more structured and maintainable object-oriented programs in Python.