In the below code Class B inherits from Class A, and the variables of Class A are assigned through Class B. I have created two new instances of Class B using Check1 and Check2 as shown below:
class ClassA:
def __init__(self, a, b):
self.A = a
self.B = b
class ClassB(ClassA):
def __init__(self, a, b):
ClassA.A = a
ClassA.B = b
def printB(self):
print("B = "+str(ClassA.A + ClassA.B))
if __name__ == '__main__':
print('#### Part I - using Check1 ######')
Check1 = ClassB(1,2)
Check1.printB()
print('#### Part II - Using Check2 ######')
Check2 = ClassB(5,6)
Check2.printB()
print('#### Part III - Again Using Check1 ######')
Check1.printB()
I get the following output:
#### Part I - using Check1 ######
B = 3
#### Part II - Using Check2 ######
B = 11
#### Part III - Again Using Check1 ######
B = 11
My question is why do I get B=11 when calling the Check1 in Part III ? Shouldn't python be creating a new instance of even the parent class for Check1 object, and shouldn't Check1 display the output as B=3 ?
How can I modify the above code so that Check1 can have value as B=3 when I call it in Part III?
ClassBconstructor. Whatever value you passed in last is now shared by the entire class.ClassAhere. Every reference toClassA.A(for example) is to exactly the same class attribute.