[英]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.