relationship we have been able to model with classes
the relationship that we’ve modeled so far is know as the “has a” relationship
class hierachy
`Animal` base class
↑
`Lizard` `Dog` derived class
↑
`poodle`
# animal.py
class Animal:
def __init__(self):
print("You made an Animal")
self.age = 0
def eat(self):
print("Animal eating...")
def sleep(self):
print("Animal is sleeping...")
# dog.py
from animal import Animal
class Dog(Animal):
# omit __init__ for a minute
def __init__(self):
# call aninmal's init
super().__init__(self)
self.breed = 'not set'
print("You made a dog")
def do_trick(self):
print("Dog doing trick!")
def sleep(self):
print("ruf. roof. roooof. rof.")
print("dog is sleeping")
# main.py
from animal import Animal
from dog import Dog
def play_with_animal(some_animal):
some_animal.eat()
some_animal.sleep()
def main():
my_animal = Animal()
my_dog = Dog()
play_with_animal(my_animal)
# polymorphism - the coee you executing is called on the fly based on how its define
# it lets the object decide which version of the medthod to execute
play_with_animal(my_dog)
# do stuff with Animal
my_animal.eat()
my_animal.sleep()
# my_animal.do_trick() AttributeError: 'Animal' object has no attribute 'do_trick'
# do stuff with Dog
my_dog.eat()
my_dog.sleep()
my_dog.do_trick()
print(my_animal.age)
# print(my_dog.age) AttributeError: 'Dog' object has no attribute 'age'
print("end")
main()
owner@morgan source % python3 main.py
You made an Animal
You made an Animal
Animal is eating...
Animal is sleeping...
Animal is eating....
ruf. roof. roooof. rof.
dog is sleeping
end
owner@morgan source % python3 main.py
You made an Animal
You made an Animal
Animal is eating...
Animal is sleeping...
Animal is eating...
ruf. roof. roooof. rof
end
place the following into a class hieracy
✓ jet plane
✓ car
sail boat
✓ airplane
✓ race car
vehicle
segway
helicopter
boat
[vehicle]
↑
[car] [boat] [airplane]
↑
[race car]