Python Inheritance¶
Inheritance allows us to define a class that inherits all the methods and properties from another class.
- Parent class (Base class): The class being inherited from.
- Child class (Derived class): The class that inherits from another 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¶
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child 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:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
Multiple Inheritance
Unlike some languages, Python supports Multiple Inheritance, where a child class can inherit from more than one parent class: class Child(Parent1, Parent2):.