Sobes.tech
Junior — Middle

What methods are used to implement abstract classes in Python?

sobes.tech AI

Answer from AI

In Python, abstract classes are implemented using the abc module (Abstract Base Classes). The main way is to create a class that inherits from abc.ABC, and declare abstract methods using 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):
        print("Bark")

# Attempting to instantiate Animal will cause an error
# animal = Animal()  # TypeError

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

You can also use @abstractproperty for abstract properties. This approach ensures that subclasses implement the necessary methods and properties.