Junior — Middle
Have you had experience using abstract classes in your projects?
sobes.tech AI
Answer from AI
Yes, in Python projects I have used abstract classes to define a basic interface and common logic that subclasses must implement. This helps ensure consistency and avoid code duplication.
In Python, abstract classes are created using the abc module and the @abstractmethod decorator.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof"
class Cat(Animal):
def make_sound(self):
return "Meow"
# animal = Animal() # Error, cannot instantiate an abstract class
dog = Dog()
print(dog.make_sound()) # Outputs: Woof
This approach helps ensure that all subclasses implement the necessary methods.