Composite and Hierarchy without instance shared variables

268 views Asked by At

I've written a good chunk of code that relies heavily on both inheritances and composition. Now i've run into a problem where my hierarchy classes need variables to be shared to work between each other, but that causes the composited classes to be shared too, meaning my separate instances of these classes will share values where i don't want them to. I obviously suck at explaining this with words so i wrote some code.

class First(object):
    def __init__(self):
        self.subvar1 = 0
        self.subvar2 = 10

class Second(object):
    variable3 = First()

class Third(Second):
    def __init__(self):
        self.variable4 = self.variable3.subvar2

Firstinstance = Third()
Secondinstance = Third()

Firstinstance.variable3.subvar1 = 50
Secondinstance.variable3.subvar2 = 0

print Firstinstance.variable3.subvar2 #<-prints 0 but i want 10
print Secondinstance.variable3.subvar1 #<-prints 50 but i want 0

Except for dumping the hierarchy system and writing one massive class where i can prevent composited classes from having their valued shared, is there any other way for me to work around this?

2

There are 2 answers

4
bruno desthuilliers On BEST ANSWER

The problem comes from Second.variable3 being a class attribute - that is, shared by all instances of the class and it's subclasses. You want:

class Second(object):
    def __init__(self):
        self.variable3 = First()


class Third(Second):
    def __init__(self):
        super(Third, self).__init__()
        self.variable4 = self.variable3.subvar2

which yields the desired results.

0
Liteye On

One way is to add

self.variable3 = First()

into the __init__ of Third, so you can keep the First and Second unchanged and prevent these values to be shared.