Search code examples
pythonobjectmultiple-inheritance

Python Calling Super Without Multiple Inheritance - Get a new copy every time


I want to utilize the ability for multiple sub classes to share the same parent class. How do I do this without invoking multiple inheritance.

class Base(object):
    shared_thing = 'Hello'
    things = []

    def __init__(self, message):
        self.things.append(message)


class One(Base):
    def __init__(self, json_message):
        super(One, self).__init__(json_message)


class Two(Base):
    def __init__(self, message):
        super().__init__(message)


class Three(Base):
    def __init__(self, message):
        Base.__init__(self, message)


one = One('one')
print('ONE: ' + str(one.things))


one = One('one but a second time')
print('ONE: ' + str(one.things))


two = Two('two')
print('TWO: ' + str(two.things))

three = Three('three')
print('THR: ' + str(three.things))

base = Base('base again')
print('BAS: ' + str(base.things))

However, these three different initializations of super will give me reference to the same object

ONE: ['one']
ONE: ['one', 'one but a second time']
TWO: ['one', 'one but a second time', 'two']
THR: ['one', 'one but a second time', 'two', 'three']
BAS: ['one', 'one but a second time', 'two', 'three', 'base again']

I don't get super object oriented with python, so excuse me if this is the wrong approach.

Thanks!


Solution

  • You've probably meant to set things as an instance variable like so:

    class Base(object):
        shared_thing = 'Hello'
    
        def __init__(self, message):
            self.things = []
            self.things.append(message)