0

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?

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
Cestarian
  • 232
  • 4
  • 10

2 Answers2

0

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.

Liteye
  • 2,761
  • 1
  • 16
  • 16
0

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thank you! that solves my problem. Is there any downside to this that i should be aware of? (I don't even understand what this does) – Cestarian Jan 07 '14 at 14:39
  • @Cestarian: if you don't understand this code you really ought to go and do some tutorial(s) on Python's classes and OO model. – bruno desthuilliers Jan 07 '14 at 16:11
  • i just don't understand the super part of it. I looked for tutorials on classes, the problem with them is that none of the ones i found are suitable for beginners. – Cestarian Jan 08 '14 at 03:47
  • `super` is documented here: http://docs.python.org/2/library/functions.html?highlight=super#super. To make a long story short, in the above snippet, it's the equivalent of `Second.__init__(self)`, iow it calls the parent class `__init__`. If you don't do it the `Third` instance won't be properly initialized (in this case it won't have a `variable3` attribute). – bruno desthuilliers Jan 08 '14 at 08:20