Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual methods in Python

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!

like image 827
Igor Chubin Avatar asked Feb 06 '14 18:02

Igor Chubin


People also ask

What is pure virtual function in Python?

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.

What are pure virtual methods?

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.

What is pure virtual function example?

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 {

How do you write a pure virtual method?

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.


1 Answers

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

like image 93
loopbackbee Avatar answered Oct 02 '22 21:10

loopbackbee