fork download
  1. class Page(object):
  2. def __init__(self, name, pages=None):
  3. self.name = name
  4. self.pages = pages if pages is not None else []
  5. def __iter__(self):
  6. return iter(self.pages) # only immediate children
  7. def walk(self, topdown=True): # all pages recursively
  8. if topdown:
  9. yield self
  10. for page in self:
  11. for subpage in page.walk(topdown):
  12. yield subpage
  13. if not topdown:
  14. yield self
  15.  
  16.  
  17. page = Page('FirstPage', [
  18. Page('FirstChild', [
  19. Page('FirstChildChild'),
  20. Page('SecondChildChild'),
  21. ]),
  22. Page('SecondChild'),
  23. ])
  24.  
  25. for p in page.walk():
  26. print(p.name)
  27.  
Success #stdin #stdout 0.09s 10840KB
stdin
Standard input is empty
stdout
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild