【问题标题】:Iterable objects in Python [closed]Python中的可迭代对象[关闭]
【发布时间】:2019-08-20 21:07:59
【问题描述】:

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

class Vector2d:
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)
    def __iter__(self):
        return (i for i in (self.x, self.y))

v=Vector2d(1,2)
x1,x2=v 
print(x1,x2)
iv=iter(v)
print(next(iv))
print(next(iv))

【问题讨论】:

  • 你有什么问题?
  • __iter__ 返回的生成器对象确实有一个__next__ 方法。
  • 是的。因为所有可迭代对象都有__iter__方法,但只有迭代器__next__

标签: python


【解决方案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)

这确实提供了本机迭代功能——同样,以一种非常愚蠢的方式。

编辑:在较旧的 python 2.x 版本中将 next() 替换为 __next__()。具体是哪个我忘记了。

【讨论】:

  • 我投了赞成票,但我只想在您的编辑中指出,通常您不会让容器成为自己的迭代器。因此,按照最佳实践,您将拥有 ContainerClassContainerIterator,这是很多样板文件,这是生成器的一个很棒的事情,它们让我们以方便的方式制作迭代器,而不需要一个单独的班级!我在this answer 中详细说明了这一点
猜你喜欢
  • 2015-12-29
  • 2019-07-27
  • 2021-11-14
  • 2019-01-12
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-03
相关资源
最近更新 更多