Inheritance in Object Oriented Programming using Python

Inheritance in Object Oriented Programming using Python

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

Inheritance in Object Oriented Programming using Python

Here a simple example of inheritance in Python is

I declare a class A

class A:
a=10

Class B inherits properties of A, the syntax is very simple enclose father class in parenthesis and keep child class outside.

class B(A):
b=5

If you create an object b_ob of class B
b_ob=B()
Then you can access the variables of class A using b_ob
print(b_ob.a)
and output would be
10

The whole program is


class A: # Declare a class A
a=10
class B(A): # Declare a class B and inherits properties of A
b=5
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.


Output:
10

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
                   a1=12
                   a2=18
                  sum=a1+a2
                  return sum

class B(A):  # Class B inherits properties of A
b_sum=0
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
print(b_sum)


Output:

30

Share to Your Friend
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Be the first to comment on "Inheritance in Object Oriented Programming using Python"

Leave a comment

Your email address will not be published.


*