Junior — Middle
Have you ever created an abstract class in your programming practice?
sobes.tech AI
Answer from AI
Yes, in Python, you can create abstract classes 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. It can define abstract methods that must be implemented in the subclasses.
Example of creating an abstract class:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
# animal = Animal() # Error: cannot instantiate an abstract class
dog = Dog()
print(dog.make_sound()) # Outputs: Woof!
This approach helps define an interface and guarantees that all subclasses implement the necessary methods.