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?
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.
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With