OneCompiler

Inheritance Implementation

301

click link to inheritence.png

PYTHON CODE


class Animal:
  """A general representation of an animal."""
  
  def __init__(self,name,species):
    """Initializes an animal object."""
    self.name = name
    self.species = species
    
  def speak(self):
    """Generic animal sound."""
    print("Generic Animal Sound")
  
  def move(self):
    """Generic animal movement."""
    print("Animal is Moving")
    
    
class Dog(Animal):
  """Represents a dog, inheriting from Animal."""
  
  def __init__(self,name,breed):
    """Initializes a dog object."""
    super().__init__(name,'Dog')
    self.breed = breed
    
  def speak(self):
    """Specific dog sound."""
    print("Bow Bow.. !")
    
  def fetch(self):
    """A dog-specific action."""
    print("The Dog is Fetching")
    
    
class Bird(Animal):
  """Represents a bird, inheriting from Animal."""
  
  def __init__(self,name,wingspan):
    "Initializes a bird object."""
    super().__init__(name,'Bird')
    self.wingspan = wingspan
    
  def speak(self):
    """Specific bird sound."""
    print("Khi Khi...!")
    
  def fly(self):
    """A bird-specific action."""
    print("The Bird in Flying")
    

# Create instances of the classes
dog1 = Dog("Rocky","Golden Retriever")
bird1 = Bird("Tweety","10")

# Demonstrate inheritance and polymorphism

dog1.speak()  # Output: Woof!
dog1.fetch()  # Output: The dog is fetching.
dog1.move()  # Output: Animal is moving (inherited from Animal)
print(dog1.name)  # Output: Rocky
print(dog1.breed)  # Output: Golden Retriever

print("-"*30)

bird1.speak()  # Output: Tweet!
bird1.fly()  # Output: The bird is flying.
bird1.move()  # Output: Animal is moving (inherited from Animal)
print(bird1.name)  # Output: Tweety
print(bird1.wingspan)  # Output: 10