Python iterate object with a list of objects
- by nerd
First time poster, long time reader.
Is it possible to iterate though an object that contains a list of objects.
For example, I have the following class
Class Page(object)
def __init__(self, name):
self.name = name
self.pages = []
I then create a new Page object and add other page objects to it.
page = Page('FirstPage')
apagepage = Page('FirstChild')
anotherpagepage = Page('SecondChild')
apagepage.pages.append(Page('FirstChildChild'))
apagepage.pages.append(Page('SecondChildChild'))
page.pages.append(apagepage)
page.pages.append(anotherpagepage)
What I would like to do is
for thispage in page:
print thispage.name
And get the following output
FirstPage
FirstChild
SecondChild
FirstChildChild
SecondChildChild
So I get all the 1st level, then the 2nd, then the 3rd.
However, the following output would be find as well
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild