gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:44:21 25 4
gpt4 key购买 nike

我正在尝试编写一个 __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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com