How to improve a mixin structure in Python?
<p>I have a simple mixin structure in Python. The code should be pretty self-explaining:</p>

<pre><code>class Base:
    def __init__(self):
        pass

class MixinA:
    def __init__(self):
        self.x = 0
        self.y = 1
    def a(self):
        print('A: x = ' + str(self.x) + ', y = ' + str(self.y))

class MixinB:
    def __init__(self):
        self.x = 2
        self.z = 3
    def b(self):
        print('B: x = ' + str(self.x) + ', z = ' + str(self.z))

class MyFirstMix(MixinA, MixinB, Base):
    def __init__(self):
        Base.__init__(self)
        MixinB.__init__(self)
        MixinA.__init__(self)

class MySecondMix(MixinA, Base):
    def __init__(self):
        Base.__init__(self)
        MixinA.__init__(self)
</code></pre>

<p>I'd like to improve this a bit, so this leads to 3 questions/problems:</p>

<ol>
<li><code>MixinA</code> and <code>MixinB</code> both have a member <code>x</code>. Is there a way to make sure, each of the class sees only its own x<code>?</code> As far as I know: No, there isn't.</li>
<li>It's slightly cumbersome to call the constructor for each mixin in the mixed class. Is there a way to automatically call all constructors or to do something with the same effect?</li>
<li>Is there a way to dynamically mixin something in-line, without explicitly creating a class? I'm looking for a syntax like: <code>mix = Base() with MixinA</code></li>
</ol>

<p>If my proposed structure is completely wrong, I'm also open for other recommendations on how to handle mixins.</p>

<p>When your inheritance schemes start to suffer from these sorts of issues it's time to consider using a technique called <em>composition</em> instead. A good readable introduction to the topic <a href="https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose" rel="nofollow">here</a>. The <a href="https://en.wikipedia.org/wiki/Composition_over_inheritance" rel="nofollow">Wikipedia example</a> is a bit less accessible, but also useful if you can handle the other programming languages. <a href="http://programmers.stackexchange.com/questions/134097/why-should-i-prefer-composition-over-inheritance">This StackExchange question</a> also offers useful discussion.</p>

<p>At its simplest, rather than a class inheriting from <code>SomeParent</code> and mixing in the <code>Mixin</code> class, you instead have the <code>SomeParent</code> instances each create an instance of <code>Mixin</code> and use that to access the mixin class's functionality.</p>

python mixins