Python and object-oriented principles: inheritance

making a subclass that inherits variables of its superclass
2025-11-05 10:09
// updated 2025-11-05 12:15

Inheritance (along with encapsulation and polymorphism) form one of the three fundamental concepts of object-oriented programming:

  • it allows a subclass to take whatever variables its superclass (i.e. parent class) has
  • it also allows the subclass to include variables that the superclass does not:
class Being:
  def __init__(self, name, age, job):
    self.name = name
    self.age = age

# a subclass of Being
class Animal(Being):
  # no need to re-declare name and age again
  # but have to include them in the constructor parameters
  def __init__(self, name, age, species):
    self.species = species

# a subclass of Being
class Human(Being):
  # no need to re-declare name and age again
  # but have to include them in the constructor parameters
  def __init__(self, name, age, job):
    self.job = job

jonny = Human("Jon", 100, "engineer")
fluffy = Animal("Fluffy", 10, "cat")

print(jonny.job)
print(fluffy.species)

# Output:
# engineer
# cat

So, in the example above, when we instantiate a new Animal object, we can readily access its name and age variables ... but it has no variable for a job, unlike a Person! (Meanwhile, a Being object has no job and no species!)

The abstract syntax for a subclass thus consists of:

class Subclass(Superclass):
  def __init__(self, superInitial, subInitial):
    self.subInitial = subInitial
    # add any sub-initial variables here
⬅️ older (in textbook-python)
🐍 Python and object-oriented principles: encapsulation
newer (in textbook-python) ➡️
Python and object-oriented principles: polymorphism 🐍