Biswajit Maharana
Biswajit Maharana

Reputation: 609

How to access one class variable from another class in python?

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  

Upvotes: 2

Views: 7404

Answers (1)

glibdud
glibdud

Reputation: 7840

In your ClassB.__init__(), you're just taking a snapshot of the var1 and var2 attributes of the passed in ClassA instance. If you need to see updated values of those attributes, store the instance itself:

class ClassB(ClassA):  
    def __init__(self, class_a):  
        self.class_a = class_a
    def methodB(self):  
        print "Inside ClassB:",self.class_a.var1,self.class_a.var2  

Upvotes: 1

Related Questions