Question on ABC classes

Dieter Maurer dieter at handshake.de
Mon Oct 26 12:35:02 EDT 2020


Peter J. Holzer wrote at 2020-10-25 20:48 +0100:
>On 2020-10-22 23:35:21 -0700, Julio Di Egidio wrote:
> ...
>> and the whole lot, indeed why even subclass ABC?

You often have the case that a base class can implement
a lot of functionality based on a few methods defined
by derived classes.

An example is a mapping class (with methods such as keys, values, items,
iteration, subscription, ...). All those methods can be implemented
generically based on "__len__", "__iter__", "__getitem__" and
"__getitem__".

In those cases, you can decorate the base methods with
`abstractmethod`.


Formerly, you had `raise NotImplementedError` in the body of
those methods. If a derived class forgot to implement a required
method, the exception was raised as soon as the method was called.
With `abstractmethod` you see the problem earlier.


More information about the Python-list mailing list