__iter__ yield

duccio duvo at tiscali.it
Sun Mar 9 16:58:28 EDT 2008


Hello!
Someone knows if it's possible to make this __iter__ function with just  
one 'yield' intead of two?
Is there some simpler way to make this  __iter__ iter through all nodes?
Thanks!

class Node:
     def __init__(self, data=None):
         self.childs=[]
         self.data=data
     def appendNode(self, n):
         node=Node(n)
         self.childs.append(node)
         return node
     def __str__(self):
         return '<'+str(self.data)+'>'
     def __iter__(self):
         yield self #1
         for n in self.childs:
             for nn in n.__iter__():
                 yield nn #2

n=Node()
n.appendNode(1).appendNode(2).appendNode(3).appendNode(4)
n.appendNode(11).appendNode(22).appendNode(33).appendNode(44)
for node in n:
     print node



More information about the Python-list mailing list