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
@abstractmethoddecorator. - Located within abstract classes (classes inheriting from
ABCor with theABCMetametaclass). - 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.