Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.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_Python 2.7_Generator_Yield - Fatal编程技术网

Python 如何打印生成器对象生成的值?

Python 如何打印生成器对象生成的值?,python,python-2.7,generator,yield,Python,Python 2.7,Generator,Yield,我想把我创建的一个类变成一个无穷级数生成器 该类基本上是这样的(我省略了其他方法,因为它很大): 我想打印一系列步骤对象。所以我试了一下: def main(): step = Step(step_id=250, offset=13, danger=0) print step.next() # Generate next 4 steps in sequence. for i in xrange(4): print step.next() 但是,我

我想把我创建的一个类变成一个无穷级数生成器

该类基本上是这样的(我省略了其他方法,因为它很大):

我想打印一系列步骤对象。所以我试了一下:

def main():
    step = Step(step_id=250, offset=13, danger=0)
    print step.next()
    # Generate next 4 steps in sequence.
    for i in xrange(4):
        print step.next()
但是,我得到了以下输出:

<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
<generator object next at 0x104364cd0>
如果执行以下操作,我将获得预期的输出:

step2 = step.advance_step()
step3 = step2.advance_step()
step4 = step3.advance_step()
print step,'\n', step2,'\n', step3,'\n', step4
如何打印生成的步骤对象而不返回生成器对象

我想我做错了什么,但我看不出是什么。

A
next()
方法必须按照iterable表示的顺序返回一个值。您为每个步骤返回了一个生成器

只需返回下一个值,此处无需使用循环:

def next(self):
    ''' Yields next step in sequence. '''
    return self.advance_step()
当然,您可以将
advance\u step()
重命名为
next()

从:

从容器中返回下一个项目。如果没有其他项目,则引发
StopIteration
异常

step2 = step.advance_step()
step3 = step2.advance_step()
step4 = step3.advance_step()
print step,'\n', step2,'\n', step3,'\n', step4
def next(self):
    ''' Yields next step in sequence. '''
    return self.advance_step()