[Tutor] What are the benefits of template or abstract base classes?

Cameron Simpson cs at cskk.id.au
Mon Jun 8 04:58:48 EDT 2020


On 07Jun2020 22:02, boB Stepp <robertvstepp at gmail.com> wrote:
>Now in "4.2 Inheritance" at
>https://dabeaz-course.github.io/practical-python/Notes/04_Classes_objects/02_Inheritance.html
>
>class TableFormatter:
>    def headings(self, headers):
>        '''
>        Emit the table headings.
>        '''
>	raise NotImplementedError()
>....
>with the comment:
>
>"This class does nothing, but it serves as a kind of design specification
>for additional classes that will be defined shortly. A class like this is
>sometimes called an “abstract base class.”"

I'd note that this code may well predate the ABC stdlib classes. Or 
Beaz' use of them. So this class to my eye has two benefits:

- like the stdlib ABC or any abstract base class in general, it lets you 
  outline the methods you intend to provide and describe their 
  semantics/behaviour - just specifying things like this helps makes 
  things clear in your mind _before_ you go to write the code

- like the recommended way to write ABC methods, these methods explode 
  in your face if you haven't overridden them. This is handy if you 
  forget things. And if you're doing test driven development, or just 
  having a decent test suite, this will aid in having those tests fail 
  if the implementation is incomplete

>OTOH, this inspired me to read up a bit on actual abstract base classes
>(ABC), which *do* force the coder to implement the methods of the ABC or it
>will not allow one to instantiate the method-deficient subclass.  I can see
>some benefit to this approach.  Of course, Beazley may be planning on
>heading in the true ABC direction later in the material.

That is the nice thing about the stdlib ABC stuff: an unoverridden 
@abstractmethod will actually cause the subclass definition to fail, 
effectively like a compile time failure. Instead of some explosion at 
runtime (ideally during testing).

However, just having an abstract base class like Baez' one is probably 
good design practice, particularly if you're going to make a few 
subclasses.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list