Sobes.tech
Junior — Middle

In what cases can an abstract class be defined in Python and how is it done?

sobes.tech AI

Answer from AI

In Python, an abstract class is used when you need to define a base class with some methods that must be implemented in subclasses, but the base class itself is not meant to be instantiated.

To create an abstract class, the abc module and the @abstractmethod decorator are used.

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() would raise an error, but Dog() can be instantiated and used

An abstract class cannot be instantiated; it serves to define an interface and enforce implementation of certain methods in subclasses.