2

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  
2
  • You've got the concepts on Inheritance all wrong. First of all it doesnt make sense to create var1 and var2 in 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 Commented Jun 19, 2017 at 14:42
  • Yes later I understood it's weird. Thanks for the inputs Commented Jun 20, 2017 at 4:38

1 Answer 1

1

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  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.