Skip to content
Advertisement

How to actually use the NotImplementedError in python?

I currently have a base class like so:

JavaScript

Now I have the abstract method foo that I want a user to override. So if they define a class like this:

JavaScript

So here the method foo is not over-ridden / defined in the DerrivedClass and when I create an object of this type it throws me a TypeError but I want to throw a NotImplementedError. How do I go about this.

The Current Error:

JavaScript

Advertisement

Answer

The problem is, that your error

JavaScript

is thrown the moment, your instace is created. When a method is declared as @abstractmethod it there must be a overwrite-method in classes inheriting this parent-class. Otherwise python will throw an error as soon as a instance of the child-class is created.

If you want your code to throw a NotImplementedError you need to remove the @abstactmethod decorator.

Abstract methods can not be called. There is no way the line raise NotImplementedError() is ever reached as log as it is a @abstactmethod.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement