Python and object-oriented principles: polymorphism

different objects with the same variable names
2025-11-05 12:09
// updated 2025-11-05 12:23

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

  • meaning "many forms", it allows several classes to share the same variable names but have them do different things

Take for example:

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
  def respond(self):
    print("Grunt!")

# 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
  def respond(self):
    print("Hello!")

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

for being in (jonny, fluffy):
  being.respond()

# Output:
# Hello!
# Grunt!

So, in the example above, when passing different kinds of Being objects through a loop, we can still have each object use its respective "respond" function, which each does a different thing!

⬅️ older (in textbook-python)
🐍 Python and object-oriented principles: inheritance
newer (in textbook-python) ➡️
Python strings 🐍
newer (in code) ➡️
Python strings 🐍
newer (posts) ➡️
Python strings 🐍