What is the ideologically correct way of implementing pure virtual methods in Python?
Just raising NotImplementedError
in the methods?
Or is there a better way?
Thank you!
A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax. For example: class Base {
A pure virtual function doesn't have the function body and it must end with = 0 . For example, class Shape { public: // creating a pure virtual function virtual void calculateArea() = 0; }; Note: The = 0 syntax doesn't mean we are assigning 0 to the function.
While it's not uncommon to see people using NotImplementedError
, some will argue that the "proper" way to do it (since python 2.6) is using a Abstract Base Class, through the abc
module:
from abc import ABCMeta, abstractmethod
class MyAbstractClass(object):
__metaclass__=ABCMeta
@abstractmethod
def my_abstract_method():
pass
There's two main (potential) advantages in using abc
over using NotImplementedError
.
Firstly, You won't be able to instantiate the abstract class (without needing __init__
hacks):
>>> MyAbstractClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyAbstractClass with abstract methods my_abstract_method
Secondly, you won't be able to instantiate any subclass that doesn't implement all abstract methods:
>>> class MyConcreteClass(MyAbstractClass):
... pass
...
>>> MyConcreteClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyConcreteClass with abstract methods my_abstract_method
Here's a more complete overview on abstract base classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With