super()
A dog has something other pets don't: a breed. To store it, Dog needs an __init__ of its own. But a method in a child class replaces the parent's, and that goes for __init__ too. Pet's __init__ then doesn't run, and the dog never gets a name:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
class Dog(Pet):
def __init__(self, name, age, breed):
self.breed = breed
rex = Dog("Rex", 3, "beagle")
print(rex.breed)
print(rex.name)beagle
Traceback (most recent call last):
File "<exec>", line 13, in <module>
AttributeError: 'Dog' object has no attribute 'name'The child's __init__ has to run the parent's as well. You get to the parent class with super():
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
class Dog(Pet):
def __init__(self, name, age, breed):
super().__init__(name, "dog", age)
self.breed = breed
rex = Dog("Rex", 3, "beagle")
print(rex.name, rex.species, rex.age, rex.breed)Rex dog 3 beaglesuper().__init__(name, "dog", age) runs Pet's __init__ for this dog, and it stores the name, the species and the age. The next line then stores what only a dog has, its breed. You don't pass self, as in any call of a method.
Look at what the dog passes as the species: always "dog". Every Dog is a dog, so you no longer have to say so when you create one: Dog("Rex", 3, "beagle"). The child's __init__ can have other parameters than the parent's, as long as it gives the parent what the parent needs.
A typical mistake is to pass the values of one particular dog: super().__init__("Rex", "dog", 3). Every dog would then be Rex. Pass the parameters, name and age.
Instructions
- 1
The program prints the breed and then ends with an
AttributeError, because the__init__ofDogdoesn't run the one ofPet. Fix it withsuper().__init__(), so that every dog gets the species"dog". The program then printsbeagleandRex (dog, 3 years). Keep the linerex = Dog("Rex", 3, "beagle")as it is. - 2
A cat needs no attribute of its own here, but it should get its species by itself too. Write a class
Catthat inherits fromPet, with an__init__that takes onlynameandageand passes the species"cat"tosuper().__init__(). At the end, createbella = Cat("Bella", 5)and print her:Bella (cat, 5 years).