Inheritance allows us to define a class that inherits all the methods and properties from another class. This promotes code reuse and logical hierarchy.
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:
// 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
passkeyword when you do not want to add any other properties or methods to the class.
super() FunctionPython 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
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.
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.
Which built-in function allows a child class to automatically inherit methods from its parent?