Python Inheritance
Inheritance:
- Inheritance allows you to make classes that build off of another class, so they can share some functionality
- The child class can perform the functions and access the variables of the parent class, but teh parent can't access those of the child class
Overriding a parent function:
- Overriding a function is when a child class redefines a function that was defined in their parent class with the same name
- Then the child objects will perform the function differently from the parent objects, each as defined in its own class
- In this example, the outputs will be "Running a child class function" and "Running a parent class function"
Accessing Overrided Parent Functions/Constructor (super):
- When created, both constructors will be called in this example, the output will be "Init parent" and "Init child"
- This is useful when you want to define a custom child class constructor that doesn't ignore the parent constructor
- If the child class doesn't define a constructor, the parent constructor will be called when the child class object is initiated
Challenge
Create a class called "Bird" which stores the weight, height, and wingspan. Make a constructor that fills those values according to parameters. Make the functions "makeSound" and "fly"; "makeSounds" should display "chirp chirp", and the function "fly" should display "flap flap". Then create two child classes "Hawk" and "Sparrow". In the hawk class, add a function called "hunt" which will display "hunting", and change the inherited "makeSound" class to display "*majestic scream*" In the sparrow class, add a function called "findSeeds" which will display "finding seeds". Now in main, create an object (instantiation) of each class and have them both perform their functions.