- INHERITANCE:
The process of acquiring properties and behaviours from one class to another class.
- PARENT CLASS:
Class which provides properties and behaviours is called “parent class (or) super class (or) base class”.
- CHILD CLASS :
Class who receives properties and behaviours from another class is called child class (or) sub class (or) derived class”.
Ex-1:
class Parent(): def m1(self): print(“hello”) class Child(Parent): def m2(self): print(“hai”) p= Parent() p.m1 c=child() c.m1 c.m2
- We can access both parent class members and child class members by creating object to the child class.
- If we create a object for child class then we can access only parent class members.
Ex-1 :
class Parent(): def m1(self): print(“hello”) class Child(Parent): def m2 (self) : super().m1() c=child() c.m2()
Ex-2:
class Parent(): a,b=10,20 class Child(Parent): x,y=100,200 def m2(self,I,j) print(i+j) print(self.x+self.y) print(self.a+self.b) c=child() c.m2(1,2)
TYPES OF INHERITANCE:
There are different types of inheritance and they are classified as follow:
1) Single Inheritance
2) Multiple Inheritance
3) Multi level Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance
Now these are explained as follows:
- Single Inheritance:
One parent contains one child.
Ex-1: class Myclass():
pass
class Myclass1(Myclass):
pass
- Multiple Inheritance:
One child contains more than one parent.
Ex-1: class Parent():
pass
class Parent1():
pass
class Child(Parent,Parent1):
pass
- Multi level Inheritance:
One parent contains one child.That child is parent is another child.
Ex-1: class A():
pass
class B(A):
pass
class C(B):
pass
- Hierarchical Inheritance:
Simply explained with example:
Ex-1: class A():
pass
class B(A):
pass
class C(A):
pass
- Hybrid Inheritance:
It means by adding or combining all inheritance such as hierarchical and multiple inheritance is called hybrid inheritance.
PROGRAMS ON INHERITANCE:
-
class A():
pass class B(A): a=10 b=20 def m1(self,a,b): print(a+b) print(self.a+self.b) b=B() b.m1(100,200)
-
class A():
a=10 b=20 class B(A): a=1000 b=2000 def m1(elf,a,b): print(super().a+super().b) print(a+b) print(self.a+self.b) b=B() b.m1(100,200)
If parent class instance variable name and child class instance variable name is same.Then we can access the parent class by using super().