如何打印发电机对象产生的价值?

时间:2016-07-19 18:44:26

标签: python python-2.7 generator yield

我试图将我创建的类创建为无限级数生成器。

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

class Step(object):
    ''' A Step taken through a field. '''
    def __init__(self, step_id, offset, danger,
        danger_limit=None, is_encounter = None, input=None):
        self.step_id = step_id
        self.offset = offset
        self.danger = danger
        self.is_encounter = is_encounter
        self.rnd = self.get_rnd(self.step_id, self.offset)
        self.danger_limit = self.get_danger_limit(self.rnd)

    def __repr__(self):
        return '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}'.format(
            self.step_id, self.offset, self.danger,
            self.rnd, self.danger_limit, self.is_encounter, self.input)

    def __iter__(self):
        return self

    def advance_step(self, danger_inc=113):
        ''' To help with generator functions. '''
        # Advances the current step, so make a current step object.
        old_Step = Step(step_id=self.step_id, offset=self.offset, danger=self.danger)

        step_id = Step.get_step_id(old_Step.step_id)
        offset = Step.get_offset(step_id, old_Step.offset)
        danger = Step.get_danger(danger_inc, old_Step.danger, old_Step.danger_limit)
        new_step = Step(step_id = step_id, offset = offset, danger = danger)
        new_step.is_encounter = Step.is_encounter(new_step.danger,
            new_step.danger_limit)
        return new_step

    def next(self):
        ''' Yields next step in sequence. '''
        while True:
            yield self.advance_step()

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

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>

预期输出应该看起来像一系列Step对象:

0   250 13  2048    0   74  19200   False   None
1   252 13  2048    2048    216 55552   False   None
2   254 13  2048    4096    163 41984   False   None
3   0   26  2048    6144    151 38912   False   None
4   2   26  2048    8192    212 54528   False   None

如果我执行以下操作,我会得到预期的输出:

step2 = step.advance_step()
step3 = step2.advance_step()
step4 = step3.advance_step()
print step,'\n', step2,'\n', step3,'\n', step4

如何打印生成的步骤对象而不返回生成器对象?

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

1 个答案:

答案 0 :(得分:2)

next()方法必须在iterable表示的序列中返回一个值。您为每个步骤返回了一个生成器。

只需返回下一个值,就不需要在这里使用循环:

def next(self):
    ''' Yields next step in sequence. '''
    return self.advance_step()

您当然可以将advance_step()重命名为next()

来自iterator.next() documentation

  

从容器中返回下一个项目。如果没有其他项目,请提出StopIteration例外。