Abstract method not implemented
A subclass of `RuntimeError`, this is meant to be raised by abstract methods in a base class to indicate that they must be implemented by a subclass.
- 1Calling a method on a subclass that has not overridden an abstract method from its parent class.
- 2A developer has defined a method as a placeholder that is not yet implemented.
- 3Trying to instantiate a class that is intended to be abstract without providing implementations for all its abstract methods.
This error is raised when a method in a base class is called, but the subclass being used has not provided its own implementation for it.
class Shape:
def get_area(self):
raise NotImplementedError("Subclasses must implement this method")
class Square(Shape):
def __init__(self, side):
self.side = side
my_shape = Square(5)
my_shape.get_area() # The 'get_area' method was not implemented in Square
expected output
Traceback (most recent call last): File "<stdin>", line 11, in <module> File "<stdin>", line 4, in get_area NotImplementedError: Subclasses must implement this method
Fix 1
Implement the required method in the subclass
WHEN You are creating a concrete subclass of an abstract base class.
class Shape:
def get_area(self):
raise NotImplementedError("Subclasses must implement this method")
class Square(Shape):
def __init__(self, side):
self.side = side
def get_area(self): # Implementation added
return self.side * self.side
my_square = Square(5)
print(my_square.get_area())
Why this works
By providing a concrete implementation of `get_area` in the `Square` class, you override the abstract method from the `Shape` base class, fulfilling the contract.
Fix 2
Use the `abc` module for formal abstract base classes
WHEN You want to enforce implementation at instantiation time rather than at runtime.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def get_area(self):
pass
class Square(Shape):
# If get_area is not implemented here, you will get a TypeError
# when you try to instantiate Square.
def get_area(self):
return 0
# square = Square() -> This would fail if get_area was not implemented.
Why this works
The `abc` module provides a more robust way to create abstract base classes. It prevents instantiation of any subclass that doesn't implement all abstract methods, catching the error earlier.
class Base:
def method(self):
raise NotImplementedError
Base().method() # NotImplementedErrortry:
obj.method()
except NotImplementedError:
print("This method is not yet implemented")from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def method(self): pass # enforced at instantiation time✕ Catching `NotImplementedError` and ignoring it
This error signals a fundamental flaw in your class structure. Ignoring it means your program is continuing with an incomplete or incorrect implementation, which will lead to bugs.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev