Middle
How is an abstract class implemented in Python?
sobes.tech AI
Answer from AI
In Python, abstract classes are implemented using the abc module (Abstract Base Classes). An abstract class is a class that is not intended to be instantiated directly but serves as a template for subclasses.
To create an abstract class:
- Inherit the class from
abc.ABC. - Use the
@abstractmethoddecorator for methods that must be implemented in subclasses.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Bark"
class Cat(Animal):
def make_sound(self):
return "Meow"
# animal = Animal() # Error: cannot instantiate an abstract class
dog = Dog()
print(dog.make_sound()) # Outputs: Bark
Thus, abstract classes help define an interface and ensure that subclasses implement the necessary methods.