OneCompiler

Polymorphism Implementation in Python

651

click to View polymorphism.png

PYTHON CODE

class Animal:
  """Abstract base class for animals"""
  def __init__(self,name):
    self.name = name
  
  def speak(self):
    """Generic animal sound."""
    print("Generic Animal Sound")
    

class Dog(Animal):
  """Represents a dog."""
  
  def speak(self):
    """Dog sound."""
    print("Woof!")
  
    
class Cat(Animal):
  """Represents a cat."""
  
  def speak(self):
    """Cat sound."""
    print("Meow!")
  
    
class Bird(Animal):
  """Represents a bird."""
  
  def speak(self):
    """Bird sound."""
    print("Tweet!")
    
    
#Create instances of different animal types
animals = [Dog("Buddy"),Cat("Whiskers"),Bird("Tweety")]


# Loop through the animals and call the speak() method on each
for animal in animals:
  print(f"{animal.name}: ")
  animal.speak()
  print('--' * 15)