I have a number of different classes with different responsibilities that do not share any methods. But, I want to share some variables that are common amongst all of them. To achieve this goal I have opted for inheritance, which does not seem to work as I had expected it to.
In this question a different method is proposed, but I do not like having to pass all the instances to each constructor.
In the testing I have done so far it seems that each instance of a class instantiates its own superclass instance. Thus, no variables are shared among the classes, but split in the instances.
An MWE to explain:
class Parent:
def __init__(self):
self.var1 = None
class Child1(Parent):
def __init__(self, var1):
super().__init__()
self.var1 = var1
class Child2(Parent):
def __init__(self, var1):
super().__init__()
self.var1 = var1
child1 = Child1(1)
child2 = Child2(2)
print(child1.var1) # prints 1
print(child2.var1) # prints 2
I am new to python, but it seems I have the wrong understanding.
The behavior I was expecting is that both times 2 would be printed, since child2 is instantiated last, thus setting var1=2 for child1 as well.
How do I make the subclasses share the same superclass instance & variables? Do I have to instantiate from the superclass down and not up from the subclasses?
EDIT: Whoops, sorry that I'm a beginner Karl! Guess I'll check out composition then..
explicit is better than implicit. The class used for the common data, used via composition, is still helping you organize the code.super, you are not instantiating. You are initializing. The object, including its base, already exists at this point.Child1orChild2instance, to use the same existingParentinstance as a base. But they cannot do that because there isn't an existingParentinstance to have in common. You could use per-class rather than per-instance data, but that is harder than just passing things around, and also loses you flexibility (what if you have aChild1and aChild2that should share one piece of data, and then a secondChild1andChild2that should share a different piece?)