Is it possible in Python to declare that method must be overridden?

Question:

I have an “abstract” class, such as:

class A:
    def do_some_cool_stuff():
        ''' To override '''
        pass

    def do_some_boring_stuff():
        return 2 + 2

And class B, subclassing A:

class B(A):
    def do_stuff()
        return 4

Is there any way to declare, that a method A.do_some_cool_stuff must be overriden, and, possibly that some warning should be raised while trying to create B-class object, when B had not implemented A.do_some_cool_stuff?

Asked By: utter_step

||

Answers:

Yes, by defining A as an ABC (Abstract Base Class):

from abc import ABC, abstractmethod

class A(ABC):

    @abstractmethod
    def do_some_cool_stuff():
        ''' To override '''
        pass

    def do_some_boring_stuff():
        return 2 + 2

You can subclass A, but you can only create instances of such a subclass if the do_some_cool_stuff() method has a concrete implementation:

>>> from abc import ABC, abstractmethod
>>> class A(ABC):
...     @abstractmethod
...     def do_some_cool_stuff():
...         ''' To override '''
...         pass
...     def do_some_boring_stuff():
...         return 2 + 2
... 
>>> class B(A):
...     def do_stuff():
...         return 4
... 
>>> B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class B with abstract methods do_some_cool_stuff
Answered By: Martijn Pieters