Python iterate object with a list of objects
Posted
by
nerd
on Stack Overflow
See other posts from Stack Overflow
or by nerd
Published on 2012-10-23T04:16:11Z
Indexed on
2012/10/23
5:04 UTC
Read the original article
Hit count: 88
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
© Stack Overflow or respective owner