Introduction to Multiple Inheritance in Python
Inheritance in Python is inheriting the attributes and methods of one class by another class. Multiple inheritances are when a child’s class is derived from two or more parent classes.
The word goes by its meaning. Just as we inherit certain features from our parents or grandparents and have our own additional features, similarly in the inheritance concept of object-oriented programming, the methods or attributes are also inherited from other classes along with certain additions to the current class.
TABLE OF CONTENT
- INHERITANCE CONCEPT IN BRIEF
- MULTIPLE INHERITANCE
- OVERRIDING
- MULTILEVEL INHERITANCE
- REAL-LIFE USE CASE
- SUMMARY
Best-suited Programming courses for you
Learn Programming with these high-rated online courses
INHERITANCE CONCEPT IN BRIEF
Inheritance in python is inheriting the attributes and methods of one class by another class. The class from which the methods and attributes get inherited is called the parent case or the base class. The class which will inherit the methods and attributes is called the child class. Inheritance is used to reuse the code.
Example –
class parent: a = 10 class child(parent): b = 20 parent_object = parent() print('Attribute of parent - ', parent_object.a) child_object = child() print('\nAttribute of child - ', child_object.b) print('Attribute inherited by child from parent - ', child_object.a)
Output –
Attribute of parent – 10
Attribute of child – 20
Attribute inherited by child from parent – 10
Here, the child class inherits the parent class. The inherited class is written inside the brackets by the side of the child class. The parent class has one attribute of a, and the child class has one attribute of b. The object of the parent class is initiated to access the attribute of the parent class. Similarly, an object of the child class is created to access the attribute of the child as well as the parent class. Now, if you try to access the attribute of the child class (that is b) from the parent class then you will get an attribute error which will show – the parent object has no attribute b.
In python, we need to write a pass inside the class or function code block if we are not writing any code inside of it. Hence, A is the parent class and B is inherited from A.
Now, it is not necessary to have some property or function inside the child’s class. The child class can inherit from the parent class without having any code in it.
Example –
class parent: a = 10 class child(parent): pass parent_object = parent() print('Attribute of parent - ', parent_object.a) child_object = child() print('Attribute inherited by child from parent - ', child_object.a)
Output –
Attribute of parent – 10
Attribute inherited by child from parent – 10
Thus, the child class derives and accesses the properties of the parent class without having any property of its own.
Till now, we have done single-level inheritance, that is the inheritance performed by one child class from one parent class. It is possible to derive from multiple parent classes in python, which is known as multiple inheritances. We also have multi-level inheritance, which is when the parent class derives from another class. The below picture will clear it all –
The concept of inheritance remains the same in all. Just that we are now having different ways of inheriting. Let’s look into Multiple Inheritance in detail.
You can also explore- How to Find the Factorial of a Number Using Python
MULTIPLE INHERITANCE
Multiple inheritances are when a child’s class is derived from two or more parent classes. For example, you are inheriting some of the features from your father and some from your mother. In this case, we have to write the names of both parent classes inside the brackets of the child class. The child class will derive the properties from both of the classes.
Let’s look into an example –
class grandparent: house = 'Three storeyed building' def age(self, number): if number>70: return ('Much Older!') else: return ('Growing towards Old age.') class parent: car = 'BMW' def work(self, hours): if hours>40: return ('Very hard working!') else: return ('Average hard working!') class child(parent, grandparent): phone = 'One Plus' child_object = child() print('My house is a ',child_object.house, ' and I have a ', child_object.car, ' and a ', child_object.phone,' phone.') print('My grandparent is 78 years old. He is ', child_object.age(78)) print('My father works for 47 hours a week. He is ', child_object.work(47))
Output –
My house is a Three storeyed building and I have a BMW and a One Plus phone.
My grandparent is 78 years old. He is Much Older!
My father works for 47 hours a week. He is Very hard working!
Here, in this example, we have created a single object for the child, as the child is inheriting from both the parent and grad parent, so we can access the attributes and functions of both parents. We have created two functions – one inside the grandparent and the other inside the parent class. We have accessed those functions from the child object by passing values into those functions. This is how multiple inheritances are done.
Programming Online Courses and Certification | Python Online Courses and Certifications |
Data Science Online Courses and Certifications | Machine Learning Online Courses and Certifications |
Now, in our examples, we have used functions with different names. What would have happened if we would have used functions with similar names but in different classes? We call this concept Overriding. Let’s see what is that.
You can also explore- Variables in Python
OVERRIDING
Function overriding takes place in multiple and multilevel inheritances. In the case of multiple inheritances, the child class is derived from more than one parent class. Hence if the parent classes are having functions with a similar name, then the function of the parent class from which the child class is deriving first will replace or override the function of the other parent class.
To understand better let’s look into an example –
class dog: def sound(self): print('a Dog is barking loudly!') class cat: def sound(self): print('a cat is making noise!') class animals(dog, cat): print('Somewhere near, ', end = ' ') animal_object = animals() animal_object.sound()
Output –
Somewhere near, a Dog is barking loudly!
In this code, we have the function of sound is similar to both the dog and cat class. In the child class of animals, we are inheriting the dog class first and the cat class next, which is seen in the line – class animals(dog, cat). It is why the function from the dog class is getting executed, overriding the same function from the cat class. Now, if we write the cat class first then –
class dog: def sound(self): print('a Dog is barking loudly!') class cat: def sound(self): print('a cat is making noise!') class animals(cat, dog): print('Somewhere near, ', end = ' ') animal_object = animals() animal_object.sound()
Output –
Somewhere near, a cat is making noise!
Thus, it can be seen that the function from the cat class is overriding that of the dog class. Now if we write the same function in the child class of animals then –
class dog: def sound(self): print('a Dog is barking loudly!') class cat: def sound(self): print('a cat is making noise!') class animals(cat, dog): print('Somewhere near, ', end = ' ') def sound(self): print('Animals are howling') animal_object = animals() animal_object.sound()
Output –
Somewhere near, Animals are howling
Thus, the function inside the child class overrides the function of the parent class.
From this, we can conclude that the object of the class will first look for the function in its class. If it cannot find the function in its class, it will move to the immediate parent class, which will be the one written first inside the bracket. If the function is not present inside the immediate parent, it will move to the next parent in search of the same function. Remember, overriding will only take place when the function names are the same in the derived and child classes.
The concept of overriding is the same in the multi-level inheritance as well. Let’s look into the multi-level inheritance and overriding in it now.
MULTI LEVEL INHERITANCE
Suppose there are three classes. Class two inherits from class one, and class three inherits from class two. It means that the features of class one are getting inherited by class three as well via class two. It is called multi-level inheritance.
The syntax is –
class one: pass class two(one): pass class three(two): pass
An object of class three can access the properties of classes one and two. However, only the object of class two can access the properties of class one. So, when you are deriving or inheriting a class from a base class, then the subclasses will also derive the base class features.
Example –
class features: def feature(self): print(' and I have Two Eyes,', end = ' ') print('Two Hands,', end = ' ') print('Two Legs,', end = ' ') class movement(features): def mobility(self): print(' and I Can walk!', end = ' ') print('Can eat!', end = ' ') class Humans(movement): def human(self): print('I am a human', end = ' ') class Monkey(movement): def monkey(self): print('I am a Monkey', end = ' ') Human_object = Humans() Human_object.human(); Human_object.feature(); Human_object.mobility() Monkey_object = Monkey() print('\n') Monkey_object.monkey(); Monkey_object.feature(); Monkey_object.mobility()
Output –
I am a human and I have Two Eyes, Two Hands, Two Legs, and I Can walk! Can eat!
I am a Monkey and I have Two Eyes, Two Hands, Two Legs, and I Can walk! Can eat!
In the above example, the features class gets derived by the class named movement, which in turn is derived by humans. It shows multi-level inheritance. We have another class called Monkey, which is also inheriting the class named movement, which in turn is inheriting the class features. Thus, two multi-level inheritances are present in our example. In this way, we can have as many multilevel inheritances and deriving classes as we want.
Now, what would have happened if the function inside the class named movement is also named as a feature (that is the same name as that of the class features)? In that case, function overriding will take place.
For example –
class features: def feature(self): print(' and I have Two Eyes,', end = ' ') print('Two Hands,', end = ' ') print('Two Legs,', end = ' ') class movement(features): def feature(self): print(' and I Can walk!', end = ' ') print('Can eat!', end = ' ') class Humans(movement): def human(self): print('I am a human', end = ' ') Human_object = Humans() Human_object.human(); Human_object.feature();
Output –
I am a human and I Can walk! Can eat!
Hence, the object of the human class will search for the feature function inside its class. In our case, it cannot find any function named as a feature in its class, this will make it move to its immediate parent, named as the movement here. There is a function called a feature, and thus it will call this function. Now it will move up to a class named features, inside of which it will get a function named feature, but it will not get called as this function is overridden by the same function in the class named movement.
The process by which the object of a class keeps moving up parent classes, starting from its class up to the parents, is known as MRO or Method Resolution Order. Every object in python gets inherited from the pre-built class called object, which is the main class and will be there. To look into the class hierarchy in the case of multilevel inheritance and to understand the concept of MRO, let’s look into an example –
class features: def feature(self): print(' and I have Two Eyes,', end = ' ') print('Two Hands,', end = ' ') print('Two Legs,', end = ' ') class movement(features): def mobility(self): print(' and I Can walk!', end = ' ') print('Can eat!', end = ' ') class Humans(movement): def human(self): print('I am a human', end = ' ') Human_object = Humans() Human_object.human(); Human_object.feature(); Human_object.mobility() print('\n\nHumans class MRO - ', Humans.mro()) print('\nMovement class MRO - ', movement.mro()) print('\nFeature class MRO - ', features.mro())
Output –
I am a human and I have Two Eyes, Two Hands, Two Legs, and I Can walk! Can eat!
Humans class MRO – [<class ‘__main__.Humans’>, <class ‘__main__.movement’>, <class ‘__main__.features’>, <class ‘object’>]
Movement class MRO – [<class ‘__main__.movement’>, <class ‘__main__.features’>, <class ‘object’>]
Feature class MRO – [<class ‘__main__.features’>, <class ‘object’>]
Taking the previous example, we can understand the MRO. Syntax to find the MRO is – class_name.mro(). For the class named ‘humans’, the first class is ‘humans’ followed by the second class of ‘movement’, which in turn is inherited from features, and which in turn gets inherited from the object class. Thus, you can see that the object class will be there. For the class of movement and feature, the same concept follows. According to this MRO, the object flow goes on in a multi-level inheritance, as we have seen.
REAL-LIFE USE CASE
Suppose you are working as an employee manager managing and showing the details of small employee groups. You are about to hire senior and fresher employees. For that, you need some basic details and would like to show them the details you saved for them along with the hikes they will get for their specific roles. Code for the same is –
class Detail: name, city, phone = '', '', 0 def details(self, name, city, phone): self.name = name self.city = city self.phone = phone class High_post(Detail): hike = 0 def experience(self, years): if years>5: hike = 0.80 else: hike = 0.40 return hike class Employees(High_post): def post(self, role): self.role = role print('Hi! I am working in - ', self.role) class Fresher: hike = 0 def experience(self, year): if year>0 and year<=2: hike = 0.20 else: hike = 0 return hike class New_Employee(Detail, Fresher): def post(self, role): self.role = role print('Hi! I am joining in - ', self.role) employee = Employees() employee.details('Rimita Das', 'Kolkata', 987654) employee.post('Developer position') print('My name and phone number is - ', employee.name,' and ',employee.phone, ' and I live in ', employee.city) print('I have 7 years of experience and I got a hike of - ', employee.experience(7)) print() new_employee = New_Employee() new_employee.details('Ronit Gupta', 'Delhi', 980644) new_employee.post('Analyst role') print('My name and phone number is - ', new_employee.name,' and ',new_employee.phone, ' and I live in ', new_employee.city) print('I have 1 years of experience and I got a hike of - ', new_employee.experience(1))
Output –
Hi! I am working in – Developer position
My name and phone number is – Rimita Das and 987654 and I live in Kolkata
I have 7 years of experience and I got a hike of – 0.8
Hi! I am joining in – Analyst role
My name and phone number is – Ronit Gupta and 980644 and I live in Delhi
I have 1 years of experience and I got a hike of – 0.2
The code is the same as what we have done. ‘Details’ is the name of the base class that gets inherited by all the sub-classes. Employees exhibit multilevel inheritance, and New_Employee class exhibits multiple inheritances.
Summary
Inheritance is crucial in code reusing in several ways. Inheritance is mainly three types which we have done here – single level, multi-level and multiple inheritances. Function overriding concept should be kept in mind while coding using inheritance concept, as it can cause the similar functions in parent classes to get ineffective. Overriding is useful when we want different effects for the functions with the same name at different levels. Inheritance is inheriting features, and thus, multiple and multi-level inheritance can be performed together, depending on the need.
Top Trending Article
Top Online Python Compiler | How to Check if a Python String is Palindrome | Feature Selection Technique | Conditional Statement in Python | How to Find Armstrong Number in Python | Data Types in Python | How to Find Second Occurrence of Sub-String in Python String | For Loop in Python |Prime Number | Inheritance in Python | Validating Password using Python Regex | Python List |Market Basket Analysis in Python | Python Dictionary | Python While Loop | Python Split Function | Rock Paper Scissor Game in Python | Python String | How to Generate Random Number in Python | Python Program to Check Leap Year | Slicing in Python
Interview Questions
Data Science Interview Questions | Machine Learning Interview Questions | Statistics Interview Question | Coding Interview Questions | SQL Interview Questions | SQL Query Interview Questions | Data Engineering Interview Questions | Data Structure Interview Questions | Database Interview Questions | Data Modeling Interview Questions | Deep Learning Interview Questions |
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio