Sobes.tech
Junior — Middle

How do you implement a basic abstract class in object-oriented programming?

sobes.tech AI

Answer from AI

In Python, a basic abstract class can be implemented using the abc module (Abstract Base Classes). To do this, the class inherits from abc.ABC, and abstract methods are marked with the @abstractmethod decorator. Such a class cannot be instantiated directly, and subclasses are required to implement all abstract methods.

Example:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Bark"

# animal = Animal()  # Error: cannot instantiate an abstract class

dog = Dog()
print(dog.make_sound())  # Outputs: Bark