How to write better way to python inheritance?
<p>I have written this,</p>

<pre><code>class Sp():
  def __init__(self):
    self.price = 1
class A(Sp):
  def __init__(self):
    super(A, self).__init__()
    self.test = True
class B(A):
  pass
class C(A):
  pass
class D(A):
  """In this class I don't want to inherit Sp class, but need A class"""
  def __init__(self):
     super(D, self).__init__()
     self.me = 'ok'
     self.list_ = [Sp()]
</code></pre>

<p><strong>Sp</strong> is the Parent class for <strong>A</strong>. And I'm using <strong>A</strong> class in <strong>B</strong>,<strong>C</strong> and <strong>D</strong>, But <strong>D</strong> don't need Sp inheritance instead it needs <strong>Sp</strong> instance object inside <strong>D</strong>(Please look into <strong>D</strong> class). I want to stop <strong>Sp</strong> inheritance in <strong>D</strong>, is there any good way to write this ?</p>

<p>You can't inherit from <code>A</code> without inheriting from <code>Sp</code> if <code>A</code> itself inherits from <code>Sp</code>. You could try to work around it though, by making <code>A</code> inherit from two classes, one of which implements the non-<code>Sp</code> behaviors (say, call it <code>Abits</code>), and <code>Sp</code> (<code>class A(Abits, Sp):</code>). Then have <code>B</code> and <code>C</code> inherit <code>A</code>, while <code>D</code> inherits solely from <code>Abits</code>.</p>

<p>If <code>A</code> doesn't need to be created independently, you could just make <code>A</code> not inherit from <code>Sp</code> at all, and have <code>B</code> and <code>C</code> inherit from both <code>A</code> and <code>Sp</code> (<code>class B(A, Sp):</code>), while <code>D</code> only inherits from <code>A</code>, which saves the need for a separate <code>Abits</code>.</p>

<p>Lastly, you might consider composition. Have <code>D</code> not inherit from anything, just contain an instance of <code>A</code>. Then use <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow">the <code>__getattr__</code> special method</a> to get attributes from <code>A</code> when they're not defined on <code>D</code>:</p>

<pre><code>class D(object):  # Explicitly inheriting from object not needed on Py3
    def __init__(self, ...):
        self.a = A(...)

    def __getattr__(self, name):
        # Only called when attribute "name" doesn't exist on instance of D
        return getattr(self.a, name)
</code></pre>

<p>You might also need to use <code>__setattr__</code> if you need to mutate the <code>A</code> instance. This is trickier (because <code>__setattr__</code> is called unconditionally, not just when an attribute doesn't exist), but there are plenty of examples of using it available if you search.</p>

python inheritance