Python Fundamentals ยท Objects, Errors and Generators
A Dog is an Animal; a Puppy is a Dog. Child classes reuse the parent's code, override what differs, and extend it with super().
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def intro(self):
return self.name + " says " + self.speak()
class Dog(Animal):
def speak(self): # overrides Animal.speak
return "woof"
class Puppy(Dog):
def speak(self):
return super().speak() + " (squeaky)" # extends the parent's version
pets = [Animal("generic"), Dog("rex"), Puppy("bit")]
for pet in pets:
print(pet.intro())Animal. Its methods are stored, but none of them run yet.class Animal belongs to it.__init__ is stored in Animal. It runs only when it is called on an object.speak is stored in Animal. It runs only when it is called on an object.intro is stored in Animal. It runs only when it is called on an object.Animal is now defined, ready to make objects from.class Dog belongs to it.speak is stored in Dog. It runs only when it is called on an object.Dog is now defined, ready to make objects from.class Puppy belongs to it.speak is stored in Puppy. It runs only when it is called on an object.Puppy is now defined, ready to make objects from.name with the value 'generic' is added to the Animal that self points to.name with the value 'rex' is added to the Dog that self points to.name with the value 'bit' is added to the Puppy that self points to.pet.intro(), with self = {name: 'generic'}. It gets its own names."...".speak() has finished, so its names are gone.intro() has finished, so its names are gone. It prints generic says ....pet.intro(), with self = {name: 'rex'}. It gets its own names."woof".speak() has finished, so its names are gone.intro() has finished, so its names are gone. It prints rex says woof.pet.intro(), with self = {name: 'bit'}. It gets its own names.speak(), with self = {name: 'bit'}. It gets its own names."woof".super().speak() + " (squeaky)" # extends the parent's version.speak() has finished, so its names are gone.intro() has finished, so its names are gone. It prints bit says woof (squeaky).