Inheritance
In Python, a class that can inherit the characteristic and behavior from another class is called inheritance. The class from which another class has been derived is called the base class or parent class. The class which inherits the behavior of the class is called the derived class or child class.
Advantages of inheritance
- Reusability of code
- Code sharing
- Consistency of interface
Single inheritance
When a derived / child class inherits only from syntax, the base/parent class is called single inheritance. If it has one base/parent class and one derived / child class it is called single inheritance.
Syntax:
class A: #parent class #some code class b(A): #child class #some code
Example:
class father: # parent class def father_name(self): print("my father name is Shamsuddin") class son(father): # child class pass obj_father= father() #object for father class. obj_son=son() # object for son class. obj_son.father_name() # you access son class to father class.
Multilevel inheritance
Multilevel inheritance is the concept where a subclass inherits properties from multiple base classes. It has one base/parent class and two (or) more derived / child classes called multilevel inheritance.
Syntax:
class A: #parent class #some code class B(A): #child class #some code class C(B): #child class #some code
Example:
class g_father:# parent class def g_father_name(self): print("my father name is Shamsuddin") class father(g_father): # child class def father_name(self): print("my father name is Shamsuddin") class son(father): # child class def son_name(self): print("my name is Junaid") obj_g_father= father() # object for g_father class. obj_father= father() # object for father class. obj_son=son() # object for son class. obj_son.g_father_name() # you access son class to g_father class. obj_son.father_name() # you access son class to father class. obj_son.son_name() # you access same class.
Multiple inheritance
Multiple inheritance is the concept where a subclass / child class inherits properties from multiple base / parent classes. If it has two base / parent classes and one derived / child class it is called multilevel inheritance.
Syntax:
class A: #parent class #some code class B(A): #parent class #some code class C (A, B): #child class #some code
Example:
class father: # parent class def father_name(self): print("my father name is Shamsuddin") class mother: # parent class def mother_name(self): print("my mother name is Aarefa") class son(mother,father): # child class pass obj_father= father() # object for father class. obj_mother=mother() # object for mother class. obj_son=son() # object for son class. obj_son.father_name() # you access son class to father class. obj_son.mother_name() # you access son class to mother class. obj_mother.father_name() # This statement did not work because mother and father are parents.