I am trying to use self.var1(defined in ClassA) inside ClassB in the below code. As we know the o/p of the program will be:
Inside ClassB: 1 2
3
But when I call object1.methodA(), I am updating self.var1 value and I want that value(updated) when I am calling object2.methodB() after it. How to achieve it? I mean I want to access the latest value of self.var1 from ClassB.
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
def methodB(self):
print "Inside ClassB:",self.var1,self.var2
object1 = ClassA()
object2 = ClassB(object1)
sum = object1.methodA()
object2.methodB()
print sum
var1andvar2in both classA and classB once the latter inherits from the former (and consequently already has these properties); also, you are creating two different objects and hoping that one's attributes influences the other's, which also makes no sense. Take a look at docs on OO and inheritance first, then move on and try what you're attempting to do docs.python.org/2/tutorial/classes.html