gpt4 book ai didi

python - 迭代器也是可迭代的吗?

转载 作者:太空狗 更新时间:2023-10-29 17:05:43 26 4
gpt4 key购买 nike

我发现:

>>> a={'x':42, 'y':3.14, 'z':7}
>>> b=a.__iter__()
>>> b.__dir__()
['__next__', ..., '__iter__', ...]
>>> b
<set_iterator object at 0x7efdd4e5afc0>

迭代器总是有 __iter__ 方法吗?

根据 https://stackoverflow.com/a/9884259迭代器也是可迭代的。如果迭代器总是有 __iter__ 方法是真的吗?

最佳答案

可迭代对象需要实现 __iter__ method or a __getitem__ method :

An object can be iterated over with for if it implements __iter__() or __getitem__().

迭代器需要一个 __iter__ 方法(返回 self)和一个 __next__ 方法(我不是 100% 确定 __next__).

迭代器总是有__iter__方法是真的吗?

是的!

这也记录在 Data model 中:

object.__iter__(self)

This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.

Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see Iterator Types.

(强调我的)

关于你的第二个问题:

迭代器也是可迭代对象吗?

是的,因为它有一个 __iter__ 方法。

附加说明

除了正式的实现之外,只需检查是否可以调用 iter() 就可以很容易地检查某些东西是否可迭代:

def is_iterable(something):
try:
iter(something)
except TypeError:
return False
else:
return True

同样,可以通过检查调用某物的 iter() 是否返回自身来检查某物是否为迭代器:

def is_iterator(something):
try:
return iter(something) is something # it needs to return itself to be an iterator
except TypeError:
return False

但是不要在开发代码中使用它们,这些只是为了“可视化”。大多数情况下,您只是使用 for ... in ... 迭代某些内容,或者如果您需要迭代器,则使用 iterator = iter(...) 然后处理迭代器通过调用 next(iterator) 直到它抛出一个 StopIteration

关于python - 迭代器也是可迭代的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46106143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com