Inheritance
Some pets can do more than others. A dog wags its tail, and it barks instead of just making a sound. You could write a class Dog and copy into it everything that Pet has, but then the same code would be in two places. Instead, a class can inherit from another one:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
def speak(self):
return f"{self.name} makes a sound."
class Dog(Pet):
def speak(self):
return f"{self.name} says Woof!"
def wag(self):
return f"{self.name} wags its tail."
rex = Dog("Rex", "dog", 3)
kiwi = Pet("Kiwi", "parrot", 4)
print(rex.age)
print(rex.speak())
print(rex.wag())
print(kiwi.speak())3
Rex says Woof!
Rex wags its tail.
Kiwi makes a sound.class Dog(Pet): creates a child class of Pet, and Pet is its parent class. This is called inheritance: a dog gets everything a pet has. Dog has no __init__ of its own, so Dog("Rex", "dog", 3) runs the one from Pet, and Rex has a name, a species and an age like any other pet.
In the child class, you write only what's different:
- A new method,
wag(). Only dogs have it:kiwi.wag()ends withAttributeError: 'Pet' object has no attribute 'wag'. - A method with the same name as one in the parent,
speak(). It replaces the parent's method for dogs, and other pets still use the one inPet.
When you call a method, Python looks for it first in the object's own class, and only if it isn't there, in the parent class. rex.speak() finds speak() right in Dog, and __init__, which Dog doesn't have, comes from Pet. A dog is still a pet, so a list of pets can hold dogs too, and a loop over it calls each pet's own speak().
Instructions
- 1
Write a class
Catthat inherits fromPetand replacesspeak(): a cat saysMeow!. Then make Bella a cat:bella = Cat("Bella", "cat", 5). The output is thenRex says Woof!,Bella says Meow!andKiwi makes a sound.Keep the lines that create Rex and Kiwi as they are. - 2
Dogs can fetch, and other pets can't. Add a method
fetch()toDogthat returnsRex brings the ball back.for Rex, and printrex.fetch()at the end of the program.