Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A basic approach will use builtin data types. If I get your drift, the <code>Letter</code> object should be created by a factory with a <code>dict</code> cache to keep previously generated <code>Letter</code> objects. The factory will create only one <code>Letter</code> object for each key.</p> <p>A <code>Number</code> object can be a sub-class of <code>list</code> that will hold the <code>Letter</code> objects, so that <code>append()</code> can be used to add a child. A <code>list</code> is easy to navigate.</p> <p>A crude outline of a caching factory:</p> <pre><code>&gt;&gt;&gt; class Letters(object): ... def __init__(self): ... self.cache = {} ... def create(self, v): ... l = self.cache.get(v, None) ... if l: ... return l ... l = self.cache[v] = Letter(v) ... return l &gt;&gt;&gt; factory=Letters() &gt;&gt;&gt; factory.cache {} &gt;&gt;&gt; factory.create('a') &lt;__main__.Letter object at 0x00EF2950&gt; &gt;&gt;&gt; factory.create('a') &lt;__main__.Letter object at 0x00EF2950&gt; &gt;&gt;&gt; </code></pre> <p>To fulfill requirement 6 (constructor), here is a more contrived example, using <code>__new__</code>, of a caching constructor. This is similar to <a href="http://code.activestate.com/recipes/413717/" rel="nofollow noreferrer">Recipe 413717: Caching object creation </a>.</p> <pre><code>class Letter(object): cache = {} def __new__(cls, v): o = cls.cache.get(v, None) if o: return o else: o = cls.cache[v] = object.__new__(cls) return o def __init__(self, v): self.v = v self.refcount = 0 def addAsChild(self, chain): if self.refcount &gt; 0: return False self.refcount += 1 chain.append(self) return True </code></pre> <p>Testing the cache functionality</p> <pre><code>&gt;&gt;&gt; l1 = Letter('a') &gt;&gt;&gt; l2 = Letter('a') &gt;&gt;&gt; l1 is l2 True &gt;&gt;&gt; </code></pre> <p>For enforcing a single parent, you'll need a method on <code>Letter</code> objects (not <code>Number</code>) - with a reference counter. When called to perform the addition it will refuse addition if the counter is greater than zero.</p> <pre><code>l1.addAsChild(num4) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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