Python Inheritance

Inheritance

class MyParentClass: myParentVar = 12 def myParentFunc (self): print("running a parent class function")
class MyChildClass (MyParentClass): # Indicate the parent class myChildVar = 24 def myChildFunc (self): print("running a child class function")
childObj = MyChildClass() childObj.myChildFunc() childObj.myParentFunc() print(childObj.myChildVar) print(childObj.myParentVar)
  • 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

class MyParentClass: def myFunc (self): print("Running a parent class function")
class MyChildClass (MyParentClass): def myFunc (self): print("Running a child class function")
childObj = MyChildClass() parentObj = MyParentClass() childObj.myFunc() parentObj.myFunc()
  • 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 overridden parent functions/constructor (super):

class MyParentClass: def __init__ (self): print("Init parent")
class MyChildClass (MyParentClass): def __init__ (self): super().__init__() print("Init child")
childObj = MyChildClass()
  • When created, both constructors will be called in this example, and 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.

Completed