Using NotImplementedError instead of abstract classes
MyBase is forcing implementation of method f() in all children. This can be achieved either by using abc.ABCMeta to make f() an abstractmethod: import abc class MyBase(metaclass=abc.ABCMeta): @abc.abstractmethod def f(self, x): pass class Child1(MyBase): def f(self, x): print(x) class Child2(MyBase): pass Child1().f(4) # prints 4 Child2().f(4) # TypeError: Can't instantiate abstract class Child2 with abstract methods f MyBase() # TypeError: Can't instantiate abstract class MyBase with abstract methods f ..or alternatively, by NotImplementedError: class MyBase(): def f(self, x): raise NotImplementedError('Abstract method not implemented.') class Child1(MyBase): def f(self, x): print(x) class Child2(MyBase): pass Child1().f(4) # prints 4 Child2().f(4) # raises implementation error MyBase() # does NOT raise error Using an abstract class instead of returning NotImplementedError disallows for example accidental instantiation of MyBase(). Are there any other benefits (or drawbacks) from using an abstract class over NotImplementedError?
MyBase
is forcing implementation of method f()
in all children. This can be achieved either by using abc.ABCMeta
to make f()
an abstractmethod
:
import abc
class MyBase(metaclass=abc.ABCMeta):
@abc.abstractmethod
def f(self, x):
pass
class Child1(MyBase):
def f(self, x):
print(x)
class Child2(MyBase):
pass
Child1().f(4) # prints 4
Child2().f(4) # TypeError: Can't instantiate abstract class Child2 with abstract methods f
MyBase() # TypeError: Can't instantiate abstract class MyBase with abstract methods f
..or alternatively, by NotImplementedError
:
class MyBase():
def f(self, x):
raise NotImplementedError('Abstract method not implemented.')
class Child1(MyBase):
def f(self, x):
print(x)
class Child2(MyBase):
pass
Child1().f(4) # prints 4
Child2().f(4) # raises implementation error
MyBase() # does NOT raise error
Using an abstract class instead of returning NotImplementedError
disallows for example accidental instantiation of MyBase()
.
Are there any other benefits (or drawbacks) from using an abstract class over NotImplementedError
?