Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python是否允许递归函数?_Python_Recursion_Iterator_Generator - Fatal编程技术网

Python是否允许递归函数?

Python是否允许递归函数?,python,recursion,iterator,generator,Python,Recursion,Iterator,Generator,我试图编写一个递归遍历目录(包括子目录)的\uu iter\uuu函数,由于它的结构是任意的,我认为递归函数是一种可行的方法。但它不起作用 以下是我所拥有的: class Dummy(object): def __init__(self, directory): self.directory = directory def _iterate_on_dir(self, path): ''' Internal helper recu

我试图编写一个递归遍历目录(包括子目录)的
\uu iter\uuu
函数,由于它的结构是任意的,我认为递归函数是一种可行的方法。但它不起作用

以下是我所拥有的:

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
语句告诉我递归调用被忽略了


如何实现这一点?

现在,当您递归调用
\u iterate\u on\u dir
时,您只是在创建一个生成器对象,而不是在它上面进行迭代

修正:
self.\u迭代\u dir(完整路径)
应成为:

for thing in self._iterate_on_dir(full_path):
    yield thing
如果您使用的是Python 3,则可以将其替换为:

yield from self._iterate_on_dir(full_path)

请给出一个输入和输出的示例,以及如何调用类。您已经正确地诊断了递归问题,但是
\uuuuu iter\uuuuu
实际上是正确的。返回生成器是实现
\uu iter\uuu
的一种非常有效的方法,因为生成器是迭代器。@Blckknght当然可以。我总是忘记迭代器协议有很多选项。修好了,谢谢!