Introduction
In this chapter, we will learn about Python Inheritance.
Inheritance
In Python, we used to create new classes from existing classes. A class that can inherit the attributes and behavior from another class is called inheritance. The class from which another class has been derived is called the base class. The class which inherits the behavior of the class is called the derived class.
Advantages of inheritance
-
Reusability of code
-
Code sharing
-
Consistency of interface
Single inheritance
When a derived class inherits only from syntax, the base class is called single inheritance. If it has one base class and one derived class it is called single inheritance.
Diagram
Syntax
Example
- class father:
- def father_name(self):
- print("my father name is selvaraj")
-
- class son(father):
- pass
-
- obj_father= father()
- obj_son=son()
-
- obj_son.father_name()
Output
Multilevel inheritance
Multilevel inheritance is the concept where a subclass inherits properties from multiple base classes. It has one base class and two (or) more derived classes called multilevel inheritance.
Diagram
Syntax
- class A:
-
-
- class B(A):
-
-
- class C(B):
-
Example
- class g_father:
- def g_father_name(self):
- print("my father name is ramasamy")
-
- class father(g_father):
- def father_name(self):
- print("my father name is selvaraj")
-
- class son(father):
- def son_name(self):
- print("my name is surya")
-
-
- obj_g_father= father()
- obj_father= father()
- obj_son=son()
-
- obj_son.g_father_name()
- obj_son.father_name()
- obj_son.son_name()
Output
Multiple inheritance
Multiple inheritance is the concept where a subclass inherits properties from multiple base classes. If it has two base classes and one derived class it is called multilevel inheritance.
Syntax
- class A:
-
-
- class B(A):
-
-
- class C (A, B):
-
Example
- class father:
- def father_name(self):
- print("my father name is selvaraj")
-
- class mother:
- def mother_name(self):
- print("my father name is jayanthi")
-
- class son(mother,father):
- pass
-
- obj_father= father()
- obj_mother=mother()
- obj_son=son()
-
- obj_son.father_name()
- obj_son.mother_name()
-
- obj_mother.father_name()
Output
Conclusion
In the next chapter, we will learn about sorting in Python.