python - Python 是否允许递归 __iter__ 函数?

标签 python recursion iterator generator

我正在尝试编写一个 __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 语句告诉我递归调用被简单地忽略了。

我怎样才能做到这一点?

最佳答案

现在,当您递归调用 _iterate_on_dir 时,您只是创建一个生成器对象,而不是实际迭代它。

修复:self._iterate_on_dir(full_path) 应该变成:

for thing in self._iterate_on_dir(full_path):
    yield thing

如果您使用的是 Python 3,则可以将其替换为:

yield from self._iterate_on_dir(full_path)

关于python - Python 是否允许递归 __iter__ 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860938/

相关文章:

python - 多索引数据帧的 Pandas 设计注意事项

haskell - 为什么这个索引选择代码不起作用?

c++ - 使用递归和回溯生成所有可能的组合

python - 在 Python 中从列表和固定变量创建字典

python - 如何从django celery任务中获取数据

algorithm - 我如何为这个算法建立和解决这个递归关系?

c++ - 这个迭代器没有迭代,怎么了?

c++ - 同时遍历两个 std::lists

javascript - 迭代 JSON 对象时出现问题

python - 使用 re.findall 从一行中提取数据