Python Inheritance

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class. This promotes code reuse and logical hierarchy.


Create a Parent Class and Child Class

Any class can be a parent class. To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:

Inheritance Example

// Create a parent class
class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname

def printname(self): print(self.firstname, self.lastname)

// Create a child class inheriting from Person class Student(Person): pass

x = Student("Mike", "Olsen") x.printname()

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.


The super() Function

Python also has a super() function that will make the child class inherit all the methods and properties from its parent seamlessly. By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties.

class Student(Person):
  def __init__(self, fname, lname, year):
    super().__init__(fname, lname)
    self.graduationyear = year

Multiple Inheritance

Unlike some other popular programming languages (like Java), Python supports Multiple Inheritance. This means a child class can inherit from more than one parent class.

Multiple Inheritance

class Flyer:
  def fly(self):
    print("Flying in the sky!")

class Swimmer: def swim(self): print("Swimming in the water!") // Inheriting from both Flyer and Swimmer class Duck(Flyer, Swimmer): pass

donald = Duck() donald.fly() donald.swim()

Note: While multiple inheritance is powerful, use it carefully. Complex inheritance trees can make your code difficult to read and debug.


Exercise

?

Which built-in function allows a child class to automatically inherit methods from its parent?