【发布时间】:2015-07-03 20:26:32
【问题描述】:
我正在尝试编写一个__iter__ 函数,它应该递归地遍历一个目录(包括子目录),并且由于它的结构是任意的,我认为递归函数将是可行的方法。但它不起作用。
这是我所拥有的:
class Dummy(object):
def __init__(self, directory):
self.directory = directory
def _iterate_on_dir(self, path):
'''
Internal helper recursive function.
'''
for filename in os.listdir(path):
full_path = os.path.join(path, filename)
if os.path.isdir(full_path):
self._iterate_on_dir(full_path)
else:
yield full_path
def __iter__(self):
'''
Yield filenames
'''
return self._iterate_on_dir(self.directory)
一些print 语句告诉我递归调用被简单地忽略了。
我怎样才能做到这一点?
【问题讨论】:
-
请举例说明输入和输出以及你如何称呼你的班级。
标签: python recursion iterator generator