class Animal(object): def __init__(self, name): self.name = name def talk(self): raise NotImplementedError() class Cat(Animal): def talk(self): return 'meow' class Dog(Animal): def talk(self): return 'woof'
Let's start with a simple assignment to practice your Inheritance skills.
The objective of this assignment is to create two subclasses of
Animal will be created by passing a name, regardless of the type of Animal. For example:
garfield = Cat(name='Garfield') odie = Dog(name='Odie') print(garfield.name) # 'Garfield' print(odie.name) # 'Odie'
Every animal will have the ability to emit a sound, or as we'll friendly say it, every animal will be able to talk. That's why the
Animal class has a
talk method which is not implemented. All
Animal subclasses will have to properly implement the
talk method. This method is really simple and it just needs to return a string. A
"meow"s and a
garfield.talk() # 'meow' odie.talk() # 'woof'
test cat meows - Run Test
def test_cat_meows(): garfield = Cat(name='Garfield') assert garfield.talk() == 'meow'
test create animals - Run Test
def test_create_animals(): garfield = Cat(name='Garfield') odie = Dog(name='Odie') assert garfield.name == 'Garfield' assert odie.name == 'Odie'
test dog barks - Run Test
def test_dog_barks(): odie = Dog(name='Odie') assert odie.talk() == 'woof'