⬅ Previous Topic
Python InheritanceNext Topic ⮕
Python Encapsulation⬅ Previous Topic
Python InheritanceNext Topic ⮕
Python EncapsulationIn Python, a class can inherit from more than one parent class. This is called Multiple Inheritance.
Don't worry if this sounds confusing. Let's break it down with very simple examples.
Inheritance means one class (called the child) can use code from another class (called the parent).
With multiple inheritance, a child class can use code from two or more parent classes.
# First Parent Class
class Father:
def skills(self):
print("Father: Cooking, Driving")
# Second Parent Class
class Mother:
def hobbies(self):
print("Mother: Painting, Gardening")
# Child class inherits from both Father and Mother
class Child(Father, Mother):
pass
# Create an object of Child
c = Child()
c.skills()
c.hobbies()
Father: Cooking, Driving
Mother: Painting, Gardening
Child
class inherits from both Father
and Mother
.c
can use functions from both parent classes.c.skills()
comes from the Father
class.c.hobbies()
comes from the Mother
class.This is where it gets interesting. Python follows something called MRO (Method Resolution Order).
Let's see an example:
class Father:
def talk(self):
print("Father: I talk about sports.")
class Mother:
def talk(self):
print("Mother: I talk about arts.")
class Child(Father, Mother):
pass
c = Child()
c.talk()
Father: I talk about sports.
Father
and Mother
have a method called talk()
.Child
class inherits from Father
first.Father
and skips the one from Mother
.You can check which class Python will look at first using this:
print(Child.__mro__)
(<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)
This tells you the order in which Python will check for methods:
Child
.Father
.Mother
.object
, which is the default base class in Python.Multiple inheritance lets a class use features from more than one parent. Just remember:
__mro__
.With this knowledge, you’re now ready to understand more about Python classes and how powerful they can be!
⬅ Previous Topic
Python InheritanceNext Topic ⮕
Python EncapsulationYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.