Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I access variables from one class to another?

I am writing a program that is utilizing multiple classes. I have one class that is dedicated to determining values for a set of variables. I would then like to be able to access the values of those variables with other classes. My code looks as follows:

class ClassA(object):     def __init__(self):         self.var1 = 1         self.var2 = 2      def methodA(self):         self.var1 = self.var1 + self.var2         return self.var1   class ClassB(ClassA):     def __init__(self):         self.var1 = ?         self.var2 = ?  object1 = ClassA() sum = object1.methodA() print sum 

I use classA to initialize 2 variables (var1 and var2). I then use methodA to add them, saving the result as var1 (I think this will make var1 = 3 and var2 = 2). What I want to know is how would I have ClassB then be able to get the values for var1 and var2 from ClassA?

like image 989
user2714543 Avatar asked Nov 15 '13 04:11

user2714543


People also ask

How do you access a variable from one class to another in python?

Variable defined inside the class: For Example – self. var_name. If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.

How do you use the variable of one class to another class in Java?

value" it must be a class variable but in your code it is a local variable inside "method()". So you either need to return "value" from "method()" and print it by "obj2. method()" or move the declaration of "value" to class level, initialize it and then print it "obj2. value".


1 Answers

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):     def __init__(self):         self.var1 = 1         self.var2 = 2      def methodA(self):         self.var1 = self.var1 + self.var2         return self.var1    class ClassB(ClassA):     def __init__(self, class_a):         self.var1 = class_a.var1         self.var2 = class_a.var2  object1 = ClassA() sum = object1.methodA() object2 = ClassB(object1) print sum 

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):     var1 = 0     var2 = 0     def __init__(self):         ClassA.var1 = 1         ClassA.var2 = 2      def methodA(self):         ClassA.var1 = ClassA.var1 + ClassA.var2         return ClassA.var1    class ClassB(ClassA):     def __init__(self):         print ClassA.var1         print ClassA.var2  object1 = ClassA() sum = object1.methodA() object2 = ClassB() print sum 

Note, however, that class variables are shared among all instances of its class.

like image 109
Steinar Lima Avatar answered Sep 19 '22 18:09

Steinar Lima