Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The other answer is right, your question is more about namespaces and references than about inheritance. </p> <p>All variables in Python are references, and all object instance is a namespace. So you can do:</p> <pre><code>class C(): def __init__(self, x): self.x = x class Shared(object): def __init__(self, value): self.value = value # instances: &gt;&gt;&gt; shared1 = Shared(1) &gt;&gt;&gt; shared2 = Shared(2) &gt;&gt;&gt; c1 = C(shared1) &gt;&gt;&gt; c2 = C(shared1) &gt;&gt;&gt; c3 = C(shared2) &gt;&gt;&gt; c4 = C(shared2) # c1 and c2 sharing a reference to shared1 &gt;&gt;&gt; c1.x.value 1 &gt;&gt;&gt; c2.x.value 1 # change c2.x will reflect on c1 &gt;&gt;&gt; c2.x.value = 3 &gt;&gt;&gt; c1.x.value 3 # but not on c3, because shared1 and shared2 are distinct namespaces &gt;&gt;&gt; c3.x.value 2 </code></pre> <p>UPDATE:</p> <p>But watch out, it is easy to make a mistake:</p> <pre><code>&gt;&gt;&gt; c4.x = 4 &gt;&gt;&gt; c3.x.value 2 &gt;&gt;&gt; c4.x.value Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; AttributeError: 'int' object has no attribute 'value' &gt;&gt;&gt; </code></pre> <p>I think the state of the art would be using <a href="http://docs.python.org/library/functions.html#property" rel="nofollow">properties</a> to hide the <a href="http://docs.python.org/tutorial/classes.html#private-variables" rel="nofollow"><code>__shared_instance</code></a> in a private instance variable - so you can use c1.x instead of c1.x.value and avoid a typo like the example above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload