How to access one class variable in another class in python – Inheritance

In this program, we are going to learn How to access one class variable in another class as well as a single level inheritance in python.

You can read more: How the concept of Inheritance is implemented in Python

 Access one class variable in another class using inheritance in python

What is inheritance:

Inheritance is an important topic of object-oriented programming language. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.
the child class acquires the properties and can access all the data members and functions defined in the parent class.
Example code:

Class A:
      {   }

Class B(A):
       {  }

Create a first class with the name A and with function name method_A:

class A:
    #here a and b both are class variable of class A.
    #and initialize with 0.
    a = 0
    b = 0
    def funA(self,x,y):
        A.a = x
        A.b = y

Now create another class with the name B from where we will access the variable of class A:

class B(A):
    def __init__(self):
        #access class A variable from class B.
        print("variable of class A",A.a)
        print("variable of class B",A.b)

Create class A object and take user input:

#class A object 
object1 = A()
#user input no.
a=int(input("enter 1st number "))
b=int(input("enter 2nd number "))

Called method of class A and create child class object:




#class A method call
ob1.funA(a,b)
#class B object
ob2 = B()

whole program:

class A:
    #here a and b both are class variable of class A.
    #and initialize with 0.
    a = 0
    b = 0
    def funA(self,x,y):
        A.a = x
        A.b = y
class B(A):
    def __init__(self):
        #access class A variable from class B.
        print("variable of class A =",A.a)
        print("variable of class B =",A.b)
#class A object 
ob1 = A()
#user input no.
a=int(input("enter 1st number "))
b=int(input("enter 2nd number "))
#class A method call
ob.funA(a,b)
#class B object
ob = B()

Output:

enter 1st number 5
enter 2nd number 6
1st variable 2nd variable value is printing from class B
1st variable of class A= 5
2nd variable of class B =6

Read more tutorials,


Leave a Reply

Your email address will not be published. Required fields are marked *