Python中的可迭代对象

时间:2019-03-29 21:26:14

标签: python

某些类的实例在Python中是可迭代的,但只有dunder     “ iter ()”方法,而不是“ next ()”。

navigator

1 个答案:

答案 0 :(得分:1)

您的__iter__方法正在返回带有next函数的对象:

z = Vector2d(4, 5)

z_iter = z.__iter__()

print(type(z_iter))

for coord in z:
    print(coord)

# <type 'generator'>

正是此生成器提供了next()函数。

这是对向量类的非常愚蠢的重写:

class Vector2d:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)
        self.index = 0

    def __iter__(self):
        return self

    def next(self):
        if self.index < 2:
            ret = [self.x, self.y][self.index]
            self.index += 1
            return ret
        else:
            raise StopIteration()


v = Vector2d(1, 2)
for coord in v:
    print(coord)

这确实提供了本机迭代功能-再次,以非常愚蠢的方式。

edit:在较旧的python 2.x版本中,将next()替换为__next__()。我完全忘记了。

相关问题