Sobes.tech
Middle

How is an abstract class implemented in Python?

sobes.tech AI

Answer from AI

Abstract classes in Python are implemented using the abc (Abstract Base Classes) module. You define a class that inherits from ABC, and methods that must be implemented in subclasses are marked with the @abstractmethod decorator.

import abc

class AbstractClass(abc.ABC):
    @abc.abstractmethod
    def abstract_method(self):
        pass

    def concrete_method(self):
        # Regular method
        print("This is a concrete method")

# Attempting to instantiate AbstractClass will raise a TypeError
# obj = AbstractClass()

# Instantiating ConcreteClass is possible because it implements the abstract method
class ConcreteClass(AbstractClass):
    def abstract_method(self):
        # Implementation of the abstract method
        print("This is the implementation of the abstract method")

obj = ConcreteClass()
obj.abstract_method()
obj.concrete_method()

Using abstract classes allows you to define an interface that derived classes must adhere to, without allowing instantiation of the abstract class itself. This enforces a structure and guarantees the presence of certain methods in subclasses.