是否可以遍历包含对象列表的对象。
例如,我有以下课程
Class Page(object)
def __init__(self, name):
self.name = name
self.pages = []
然后我创建一个新的Page对象并向其添加其他页面对象。
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)
我想做的是
for thispage in page:
print thispage.name
并获得以下输出
FirstPage
FirstChild
SecondChild
FirstChildChild
SecondChildChild
所以我得到了所有的第1级,然后是第2级,然后是第3级。
但是,也会找到以下输出
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
你可以定义一个__str__
from itertools import chain
class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __str__(self):
return "\n".join(chain([self.name], map(str, self.pages)))
那么你可以只是print page
或者,如果您希望使用for循环,则可以定义迭代器
class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __iter__(self):
yield self
for page in self.pages:
for i in page:
yield i
递归地做:
class Page(object):
def __init__(self, name):
self.name = name
self.pages = []
def __iter__(self):
for p in self.get_children_pages(self):
yield p
def get_children_pages(self, start_page):
result = [start_page.name]
for this_page in start_page.pages:
result.extend(self.get_children_pages(this_page))
return result
>>>>for p in page:
.... print p
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild
递归地做
def print_all_pages(page):
print page.name
if len(page.pages) == 0 then:
return
else:
for child_page in page.pages:
print_all_pages(child_page)
def print_pages(pages_collection):
for page in pages_collection:
print_all_pages(page)
class Page(object):
def __init__(self, name, pages=None):
self.name = name
self.pages = pages if pages is not None else []
def __iter__(self):
return iter(self.pages) # only immediate children
def walk(self, topdown=True): # all pages recursively
if topdown:
yield self
for page in self:
yield from page.walk(topdown)
if not topdown:
yield self
你可以用Python <3.3替换yield from
:
for subpage in page.walk(topdown):
yield subpage
在这种情况下。
page = Page('FirstPage', [
Page('FirstChild', [
Page('FirstChildChild'),
Page('SecondChildChild'),
]),
Page('SecondChild'),
])
for p in page.walk():
print(p.name)
FirstPage
FirstChild
FirstChildChild
SecondChildChild
SecondChild