How to iterate through instances in a tree?
<p>I have a problem with a self-written tree class in python:</p>

<pre><code>class Tree:
    def __init__(self, parent=0, value=0):
        self.value = value
        self.parent = parent
    def __iter__(self): return self
    def next(self):
        tmp = self.value
        try:
            self.parent = self.parent.parent
            self.value = self.parent.value
        except AttributeError:
            raise StopIteration
        return tmp
    def sum(self):
        list_ = [item for item in self]
        print list_
        return sum(list_)
</code></pre>

<p>Actually, the "tree" is not fully written, but the current problem blocks further progress.
The structure has only two instance variables (<code>value</code>, <code>parent</code>).
I would like to sum values from the current instance to the first parent with iterators (if it is all together possible). The <code>sum</code> method is used for that (additional <code>list_</code> variable is unnecessary, but helps further to explain the problem). </p>

<p>When running a test case</p>

<pre><code>parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
print child2.sum()
</code></pre>

<p>I obtain the following:</p>

<pre><code>[10]
10
</code></pre>

<p>Please, could anybody explain why the list of values contains only one number though it should look like <code>[10,8]</code>? Seems the problem is in the implementation of <code><strong>iter</strong></code> and <code>next</code>, but I can't understand how to repair the solution.</p>

<p>Thank you in advance.</p>

<p>Here you go:</p>

<pre><code>class Tree:
    def __init__(self, parent=None, value=0):
        self.value = value
        self.parent = parent

    def __iter__(self): 
        yield self.value
        root = self
        while root.parent is not None:
            yield root.parent.value
            root = root.parent
        raise StopIteration


    def tree_sum(self):
        return sum(list(self))


parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
</code></pre>

<p>I've changed the default <code>parent</code> value to None.</p>

<pre><code>for i in child2:
    print(i)

10
8
0 # 0 is here because the parent value is 0 by default.
</code></pre>

python python-2.7