Search⌘ K

Solution Review 2: Implement an Animal Class

Explore how to implement an Animal class with name and sound properties in Python. Understand inheritance by extending Animal with Dog and Sheep classes that override methods using super(). This lesson helps you apply polymorphism and organize code modularly through method overriding and additional properties.

We'll cover the following...

Solution #

Python 3.5
class Animal:
def __init__(self, name, sound):
self.name = name
self.sound = sound
def Animal_details(self):
print("Name:", self.name)
print("Sound:", self.sound)
class Dog(Animal):
def __init__(self, name, sound, family):
super().__init__(name, sound)
self.family = family
def Animal_details(self):
super().Animal_details()
print("Family:", self.family)
class Sheep(Animal):
def __init__(self, name, sound, color):
super().__init__(name, sound)
self.color = color
def Animal_details(self):
super().Animal_details()
print("Color:", self.color)
d = Dog("Pongo", "Woof Woof", "Husky")
d.Animal_details()
print("")
s = Sheep("Billy", "Baa Baa", "White")
s.Animal_details()

Explanation

  • We implemented an Animal class, which has name and sound ...