Search code examples
pythonmixins

Multiple Mixins and properties


I am trying to create a mixin class that has it's own properties, but as the class has no init to initialize the "hidden" variable behind the property.

class Software:

    __metaclass__ = ABCMeta

    @property
    def volumes(self):
        return self._volumes

    @volumes.setter
    def volumes(self, value):
        pass

class Base(object):

    def __init__(self):
        self._volumes = None

class SoftwareUser(Base, Software):

    def __init__(self):
        super(Base, self).__init__()

So above is the best that I have come up with to solve this but the reality is that the _volumes dosn't really belong in the base. I could add an init to the Software class but then the super call wont work on both mixins.

The second is that I will need multiple mixins dependent on the incoming call they will always need the base, but the mixins will change so I dont really want variables from mixins that aren't mixed in for that call.

Is there a way that i can have the mixin add it's variables to the class if it is mixed in perhaps dynamically call the init of the mixin class ?.

Any questions let me know.

Thanks


Solution

  • Yes, that's wildly overcomplicated. A class (including mixins) should only be responsible for calling the next implementation in the MRO, not marshalling all of them. Try:

    class Software:
    
        @property
        def volumes(self):
           return self._volumes
    
        @volumes.setter
        def volumes(self, value):
           pass
    
        def __init__(self):
            self._volumes = None
            super().__init__()  # mixin calls super too
    
    
    class Base(object):
    
        def __init__(self):
            other_vars = None
    
    
    class SoftwareUser(Software, Base):  # note order
    
        def __init__(self):
            super().__init__()  # all you need here