Inheritance in Object Oriented Programming
Inheritance is the process of acquiring properties from a father class into a child class. Suppose there are two classes A and B, then if B acquires properties of A i.e variables and methods then B inherits A and this process is called inheritance.
Inheritance in Python
Here a simple example of inheritance in Python is
I declare a class A
Class B inherits properties of A, the syntax is very simple enclose father class in parenthesis and keep child class outside.
If you create an object b_ob of class B
Then you can access the variables of class A using b_ob
and output would be
The whole program is
class A: # Declare a class A
class B(A): # Declare a class B and inherits properties of A
b_ob=B() # Create an object of class of B
print(b_ob.a) # Access variable of A by using object of B and print it.
Inherit a Method from a Class
In the above example I have demonstrated inheritance of variables. In this program a method add() of class A is inherited by class B. Further, add() method is called by object of B.
class A: # Class A is declared here
def add(self): # Method add() of class A id defined here
class B(A): # Class B inherits properties of A
b_ob=B() # Object of class B b_ob is created
b_sum= b_ob.add() # Object of class B b_ob calls method of class A