Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think your workaround is doable; You could use properties to make access to <code>P</code>'s attributes easier:</p> <pre><code>class P(object): def __init__(self,name='default',pvar=1): self.pname = name self.pvar=pvar class C(object): def __init__(self,name,pobject=P()): #&lt;-- The same default `P()` is # used for all instances of `C`, # unless pobject is explicitly defined. self.cname = name self.pobject=pobject @property def pvar(self): return self.pobject.pvar @pvar.setter def pvar(self,val): self.pobject.pvar=val c1=C('1') c2=C('2') </code></pre> <p><code>c1</code> and <code>c2</code> share the same <code>pobject</code>:</p> <pre><code>print(c1.pvar) # 1 c1.pvar=2 </code></pre> <p>Notice that changing <code>pvar</code> through <code>c1</code> changes <code>c2.pvar</code>:</p> <pre><code>print(c2.pvar) # 2 </code></pre> <p><code>c3</code> has a different <code>pobject</code>:</p> <pre><code>c3=C('3',P()) print(c3.pvar) # 1 </code></pre> <hr> <p>Regarding OOP design for the psychology experiment (mentioned in the comments):</p> <pre><code>import Image class Picture(object): def __init__(self,filename): self.filename = filename self.image=Image.open(filename) class Person(object): def __init__(self,name): self.name=name # other vital statistics associated with people as individuals here class Trial(object): # A trial is composed of one person, one picture, and the places they look def __init__(self,person,picture,locations): self.person=person self.picture=picture self.locations = locations # put methods for analyzing where the person looked here </code></pre> <p>A <code>Picture</code> is certainly not a <code>Person</code>, nor vice versa. And the same goes for <code>Trial</code>s. So none of these classes should inherit from each other.</p> <p>Each of these classes have a public (and maybe a private) interface. Public methods and attributes should be freely accessible from other classes. So given a <code>Trial</code> instance, <code>t</code>, the image should be accessible through <code>t.picture.image</code>. As long as you are only accessing public attributes and methods, then everything should be fine. </p> <p>For convenience, you can use <code>properties</code> to link attributes to component-attributes. For example:</p> <pre><code>class Trial(object): ... @property def image(self): return self.picture.image </code></pre> <p>But to short-cut this by making, say, <code>Trial</code> a subclass of <code>Picture</code> would be contrary to fundamental OOP design principles.</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