繁体   English   中英

带有生成器的Python无限递归

[英]Python infinite recursion with generators

我试图将头围在python生成器上,结果,我试图使用yield打印无限嵌套的对象,但是我发现在弹出堆栈时仍然遇到问题。 理想情况下,我希望能够随需提供并打印每个项目,但我无法弄清楚自己做错了什么:

class Parent:    
    def __init__(self, name, child=None):
        self._name = name
        self._child = child

    def get_name(self):
        return self._name

    def get_child(self):
        return self._child

    def set_child(self, child):
        self._child = child

    def __iter__(self):
        next_child = self._child.get_child()
        if not next_child:
            raise StopIteration            
        else:
            self._child = next_child
            yield next_child

    def __str__(self):
        return "%s has %s" % (self._name, self._child)

if __name__ == '__main__':
    p1 = Parent("child")
    p2 = Parent("child", p1)
    p1.set_child(p2)

    for t in p1:
        print t

正如jonrsharpe指出的那样,您的代码中的错误是由于__str__函数,该函数试图返回:

child has child has child has child has child has ...

您可能是说:

def __str__(self):
    return "%s has %s" % (self._name, self._child.get_name()) 
    # return 'child has child'

同样, __iter__应该是一个生成器函数。 生成器函数需要包含一个循环才能连续产生值。 所以应该是这样的:

def __iter__(self):
    next_child = self._child.get_child()
    while next_child:            
        yield next_child
        next_child = next_child.get_child()
    # When the function ends, it will automatically raise StopIteration

进行修改后,您的代码将显示child has child连续行child has child

另请参见yield关键字在Python中做什么? 有关生成器功能的更多信息。

无限递归在__str__函数中发生。 它与__iter__函数无关。

当您print t ,它将执行t._child.__str__ ,依次执行t._child._child.__str__ ,依此类推。

尝试将__str__函数定义更改为简单的内容,例如return self._name ,您将不会得到超出递归深度的错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM