[英]Implementing recursive function with __iter__ method in a Python class
[英]Does Python allow a recursive __iter__ function?
我正在尝试编写一个__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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.