Domanda

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!

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top