Home > Software engineering >  Sharing data between different classes using inheritance
Sharing data between different classes using inheritance

Time:09-17

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..

CodePudding user response:

You are mistaking instance variables with class variables. Here, you defined instance variables because the assignation is inside the __init__ (the initialization of the instance).
What you want is to define a class variable, like so :

class Parent:
    var1 = None


class Child1(Parent):
    def __init__(self, var1):
        super().__init__()
        Parent.var1 = var1


class Child2(Parent):
    def __init__(self, var1):
        super().__init__()
        Parent.var1 = var1


child1 = Child1(1)
child2 = Child2(2)

print(child1.var1)  # prints 2 !! <-----
print(child2.var1)  # prints 2

Before, each instance had its own var1 variable, that's what an instance variable is, by definition.

But in my example, the var1 variable is defined into the class object. Each instance can reference it (using Parent.var1), but it is always the same variable. But Python is nice and lets you access class variable as if they were instance variables, which can cause confusion.

But bear in mind that this is now what inheritance is designed for. Yes, you can use that way but it is a bit unuasual.

  • Related