Python中的任何内容都不会从Iterator
或Iterable
继承,因为它们体现了协议。 Python寻找__iter__
and __next__
methods,而不是针对特定的基类。任何对象都可以是迭代器或迭代器,只需实现这些方法即可。
zip()
是C代码中定义的内置函数,它遵循所有内置函数的命名约定;这些总是小写;它返回的类型在这里并不完全相关,并且遵循函数名称。
collections.abc.Iterable
和collections.abc.Iterator
类是抽象基类;他们实现special hooks,如果您正在测试的实例或子类实现所需的方法,则实质上会返回True
。
zip()
既是可迭代(它有一个__iter__
法)和迭代器(__iter__
返回对象本身,它有一个__next__
法):
>>> from collections.abc import Iterator, Iterable
>>> zip_instance = zip('')
>>> type(zip_instance)
<class 'zip'>
>>> isinstance(zip_instance, Iterator)
True
>>> isinstance((zip_instance, Iterable)
True
>>> zip_instance.__iter__
<method-wrapper '__iter__' of zip object at 0x10f2d8348>
>>> zip_instance.__iter__() is zip_instance
True
>>> zip_instance.__next__
<method-wrapper '__next__' of zip object at 0x10f2d8348>
zip()
不是发电机,因为它不”吨有任何special generator methods的:
>>> hasattr(zip_instance, 'send')
False
>>> hasattr(zip_instance, 'throw')
False
>>> hasattr(zip_instance, 'close')
False
他们是农行的,它们不会出现在内置对象的MRO ... – 2014-10-27 14:33:26
什么都可以的迭代器。它不必从任何特定的基类型继承;它只需提供正确的方法。 – khelwood 2014-10-27 14:39:59
Python不太重视对象是什么类型,它关心对象可以做什么。 – 2014-10-27 16:14:15