Sobes.tech
Middle

What is an abstract method?

sobes.tech AI

Answer from AI

This is a method in an abstract class that is declared but has no implementation. It must be overridden (implemented) in any non-abstract subclass.

Example of usage in Python with the abc module:

from abc import ABC, abstractmethod

class Shape(ABC): // Abstract class
    @abstractmethod
    def area(self): // Abstract method
        pass

    @abstractmethod
    def perimeter(self): # Another abstract method
        pass

class Circle(Shape): # Subclass of the abstract class
    def __init__(self, radius):
        self.radius = radius

    def area(self): # Mandatory implementation of area()
        return 3.14 * self.radius ** 2

    def perimeter(self): # Mandatory implementation of perimeter()
        return 2 * 3.14 * self.radius

# Creating an instance of the abstract class Shape is impossible:
# s = Shape() # Will raise TypeError

Key points:

  • Defined using the @abstractmethod decorator.
  • Located within abstract classes (classes inheriting from ABC or with the ABCMeta metaclass).
  • Designed to ensure uniformity of interfaces within the class hierarchy.
  • The presence of an abstract method makes the class abstract, even if it does not inherit from ABC.
What is an abstract method? — Python - sobes.tech