Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Okay, I think you might want to rephrase your question as:</p> <p><strong>How can I extend Python's OOP to make inheritance work on the level of objects rather than classes?</strong></p> <p><em>First off - don't mess with the dicts:</em> If you are just copying the entries of the parent dict over to the child-dict, this works for instantiation, but changes in any of the dicts will not automagically update entries in all the other dicts. Assigning a new value to an attribute will simply create a new reference, so the attribute will not point to the same object any more. </p> <p>The solution is to tell python to look for the attribute in the right place using some Python magic ...</p> <pre><code>class ProxyMixin (object): def __init__(self, parent): self.parent = parent def __getattribute__(self, name): if name != 'parent' and hasattr(self.parent, name): return getattr(self.parent, name) else: return object.__getattribute__(self, name) def __setattr__(self, name, val): if name != 'parent' and hasattr(self.parent, name): setattr(self.parent, name) else: object.__setattr__(self, name, val) </code></pre> <p>(see the <a href="http://docs.python.org/reference/datamodel.html#attribute-access" rel="nofollow">python reference on attribute access</a>)</p> <p>Just add the ProxyMixin to your child class, and you will be fine.</p> <pre><code>class P: data = "shared data" def __init__(self, name): self.name = name def printname(self): print self.name class C(P, ProxyMixin): def __init__(self, parent=None): if parent: ProxyMixin.__init__(self, parent) </code></pre> <p>Now youn can dynamically rewire the parent object at any time using a simple assignment:</p> <pre><code>c.parent = newparent </code></pre>
 

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