Curriculum
In Python, an abstract class is a class that is meant to be subclassed, but not instantiated. It is used as a template or blueprint for other classes, which inherit its properties and methods.
An abstract class is defined using the abc
module, which stands for “Abstract Base Classes”. This module provides the infrastructure for defining abstract classes and abstract methods in Python. An abstract class can be defined by inheriting the ABC
class or by decorating a class with the @abc.ABC
decorator.
Here’s an example of how to define an abstract class in Python:
import abc class Animal(metaclass=abc.ABCMeta): @abc.abstractmethod def speak(self): pass
In this example, we define an abstract class Animal
using the abc
module. The @abc.abstractmethod
decorator marks the speak
method as abstract, which means that any subclass of Animal
must implement this method. The pass
statement inside the speak
method is a placeholder, indicating that the method does nothing but must be overridden in subclasses.
Here’s an example of how to define a subclass of the abstract Animal
class:
class Dog(Animal): def speak(self): return "Woof!"
In this example, we define a Dog
class that inherits from the abstract Animal
class. We implement the speak
method in Dog
by returning the string “Woof!”.
Now we can create an instance of the Dog
class and call its speak
method:
dog = Dog() print(dog.speak()) # "Woof!"
In this example, we create a new instance of the Dog
class and call its speak
method, which returns the string “Woof!”. Since Dog
is a subclass of Animal
, it is required to implement the speak
method defined in the abstract Animal
class.
The main use case for abstract classes in Python is to define a set of methods that subclasses should implement. This allows for a more structured and consistent approach to creating classes that share a common set of properties and behaviors. Abstract classes can help to prevent errors and ensure that all subclasses implement the required methods.