Python Abstract Base Class Example

When I program using Python, I almost never implement class inheritance. I decided to put together a demo just to refresh my memory.

I did two demos. The first demo illustrates basic inheritance syntax where the goal is to encourage code reuse (at the expense of significantly increased complexity). The second demo illustrates abstract base class inheritance where the goal is to define an interface that must be implemented.

The code for the first demo is:

# simple_python_inheritance.py

class BasePet:
  def __init__(self, name):
    self.name = name  # "Fido", "Jinx", etc.
  def set_age(self, n):
    self.age = n  # applies to all pets

class Dog(BasePet):
  def __init__(self, name, color):
    super().__init__(name)
    self.color = color
  def description(self):
    return self.name + " is a " + self.color + \
      " dog who is " + str(self.age) + "\n"

class Fish(BasePet):
  def __init__(self, name, species):
    super().__init__(name)
    self.species = species
  def description(self):
    return self.name + " is a " + \
      self.species + "\n"

print("\nBegin simple Python inheritance example \n")

d = Dog("Riley", "black")
d.set_age(8)
print(d.description())

f = Fish("Fins", "goldfish")  # instantiate success
print(f.description())  # fatal error: age is not set

print("\nEnd demo ")

There’s a BasePet class that’s intended only to act as a starting point when implementing more specific classes such as a Dog class or a Fish class. The output of the demo is:

Begin simple Python inheritance example

Riley is a black dog who is 8

Fins is a goldfish

End demo

Notice that BasePet has an age field that is used by the Dog class but which is ignored by the Fish class — probably an oversight.

To enforce implementation of methods in a derived class, I put together a second demo. This works like an Interface in other languages, notably C# and Java. The code:

# abc_python_inheritance.py

from abc import ABC, abstractmethod

class AbstractBasePet(ABC):
  def __init__(self, name):
    self.name = name
  
  @abstractmethod
  def set_age(self, n):
    pass

class Dog(AbstractBasePet):
  def __init__(self, name, color):
    super().__init__(name)
    self.color = color

  def set_age(self, n):
    self.age = n

  def description(self):
    return self.name + " is a " + self.color + \
      " dog who is " + str(self.age) + "\n"

class Fish(AbstractBasePet):
  def __init__(self, name, species):
    super().__init__(name)
    self.species = species

  # the set_age() method must be implemented

  def description(self):
    return self.name + " is a " + self.species + \
      " fish \n"

print("\nBegin ABC Python inheritance example \n")

d = Dog("Kevin", "brown")
d.set_age(7)
print(d.description())

f = Fish("Fins" "goldfish")
# "TypeError: Can't instantiate abstract class Fish
#   with abstract method set_age"
print(f.description())

print("\nEnd demo ")

The ABC module (abstract base class) allows you to define an abstractmethod that must be implemented by a derived class, or else instantiation of the derived class will immediately fail.

The output of the second demo is:

Begin ABC Python inheritance example

Kevin is a brown dog who is 7

Traceback (most recent call last):
  File "C:\Data\Junk\Python\InheritanceDemos\abc_python_
    inheritance.py", line 42, in 
    f = Fish("Fins" "goldfish")
        ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Can't instantiate abstract class Fish with abstract
  method set_age

The Fish object never instantiates, because the required set_age() method was not implemented.

I’m not sure how to articulate it clearly, but I just don’t like class inheritance. It just doesn’t feel right to me. Class inheritance has a vague feel of a solution in search of a problem. So I use it only very rarely.



For the most part, computer science is strictly objective. But a few things are subjective, like personal preferences (or not) for different programming languages and programming paradigms. I’m not a fan of class inheritance in some subjective way that I can’t explain.

Here are three old songs that feature a marimba or vibraphone or xylophone, that I find very pleasing in some subjective way that I can’t explain.


Under My Thumb The Rolling Stones (1966)



Stop! In the Name of Love The Supremes (1965)



All Summer Long The Beach Boys (1964)




This entry was posted in Machine Learning, Miscellaneous. Bookmark the permalink.

Leave a Reply