|

How to Fix: NotImplementedError in Python (OOP Guide)

3D illustration of a robot trying to use a feature that is only a blueprint outline, representing the NotImplementedError.

This error looks scary, but it’s actually a helpful message from a developer. In Python, the NotImplementedError is not a bug; it’s a feature of Object-Oriented Programming (OOP).

It means: “You are supposed to write this method yourself, but you forgot.”

The Cause: Abstract Methods

Programmers create “abstract” parent classes (blueprints) that are meant to be inherited from. They use NotImplementedError to force the child classes to create their own versions of a method.

Example: The Parent Class (The “Blueprint”)

class Shape:
    def draw(self):
        # I am a blueprint. I don't know how to draw!
        # I force my children to define this.
        raise NotImplementedError("You must implement the 'draw' method!")

The Problem Code (The “Child” Class): You inherit from Shape but forget to define your own .draw() method.

class Circle(Shape):
    def get_radius(self):
        return 10
    
    # Whoops, we forgot to add a 'draw' method!

my_circle = Circle()
my_circle.draw() # CRASH! NotImplementedError

The Fix: Implement the Method

You must “override” the parent’s placeholder method with your own real code.

Correct Code:

class Circle(Shape):
    def get_radius(self):
        return 10
    
    # HERE IS THE FIX:
    def draw(self):
        print("Drawing a circle...")

my_circle = Circle()
my_circle.draw() # Output: Drawing a circle...

If you see this error, Python is telling you that you need to go into your class and write the function that the parent class (or library) is demanding.

Similar Posts

Leave a Reply