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 the first class with the name A and with the 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 ob1 = A() #user input no. a=int(input("enter 1st number ")) b=int(input("enter 2nd number "))
Call method of class A and created 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 ob1.funA(a,b) #class B object ob2 = B()
Output:
enter 1st number 5 enter 2nd number 6 1st variable of class A= 5 2nd variable of class B =6
Read more tutorials:
This program is completely wrong it will show error ‘ob’ not defined as the object of b is defined after the function call so it will get confuse and will show the error please upload the correct solution in your website many students might see the same code and probably doubt on their intelligence
We have updated the code and it is working fine now. Thanks for your comment.