Pregunta

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!

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top