Solution 1

class Animal(object):
    def __init__(self, name): = name

    def talk(self):
        return "{name} says {sound}".format(, sound=self.sound)

class Cow(Animal):
    def __init__(self, name):
        super(Cow, self).__init__(name)
        self.sound = "moo"

class Sheep(Animal):
    def __init__(self, name):
        super(Sheep, self).__init__(name)
        self.sound = "baaaaa"

class Fox(Animal):
    def __init__(self, name):
        super(Fox, self).__init__(name)
        self.sound = "Ring-ding-ding-ding-dingeringeding"

Cow Says Moo

Extend the Animal class with three different subclasses: Cow, Sheep, and Fox.

When each animal is created, it should receive a name as a parameter. Rather than having a talk method in each subclass, you can just put one talk method in the parent Animal class and have the subclasses use that.

The talk method should say "[Animal_name] says [Animal_sound]"

Each subclass should have a sound attribute for that particular animal.

  • The sound for Cow is "moo"
  • The sound for Sheep is "baaaaa"
  • The sound for Fox is "Ring-ding-ding-ding-dingeringeding"

Try and take advantage of the super keyword in the subclasses for the __init__ method (the Animal class should only store the attribute name, but the subclasses also store the attribute sound).


sheep = Sheep("Baaab")
print(sheep.sound) # baaaaa
print( # Baaab says baaaaa

Test Cases

test animals - Run Test

def test_animals():
    cow = Cow('Bessie')
    sheep = Sheep('Fuzzy')
    fox = Fox('Red')

    assert isinstance(cow, Animal)
    assert isinstance(sheep, Animal)
    assert isinstance(fox, Animal)

    assert cow.sound == "moo"
    assert sheep.sound == "baaaaa"
    assert fox.sound == "Ring-ding-ding-ding-dingeringeding"

    assert == "Bessie says moo"
    assert == "Fuzzy says baaaaa"
    assert == "Red says Ring-ding-ding-ding-dingeringeding"
class Animal(object): pass