Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to actually use the NotImplementedError in python?

I currently have a base class like so:

from abc import ABC, abstractmethod

class BaseClass(ABC):
    @abstractmethod
    def __init__(self, param1, param2):
        self._param1 = param1
        self._param2 = param2

    @abstractmethod
    def foo(self):
        raise NotImplementedError("This needs to be implemented")

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

from BaseClassFile import BaseClass

class DerivedClass(BaseClass):
    def __init__(self, param1, param2):
        super().__init__(param1, param2)

So here the method foo is not over-ridden / defined in the DerivedClass 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:

TypeError: Can't instantiate abstract class FF_Node with abstract methods forward

like image 782
Rohan Asokan Avatar asked Oct 27 '25 15:10

Rohan Asokan


1 Answers

The problem is, that your error

TypeError: Can't instantiate abstract class FF_Node with abstract methods forward

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.

like image 117
wuerfelfreak Avatar answered Oct 30 '25 07:10

wuerfelfreak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!