2014-10-27 28 views
0

zip为例。 我只想知道它是Iterable还是IteratorGenerator在Python中查看实例的类层次结构

所以我把这个:

zip(x,y).__class__ 

它打印:ZIP
为什么类名是小写?

import inspect 
inspect.getmro(zip) 
zip.__base__ 

它打印:(拉链,对象)
那是不可能的。 Python doc表示zip返回iterator(或generator?),但zip显然不是从Iterator或根据getmro打印的内容继承而来。

所以这两个问题,谢谢你的帮助。

+2

他们是农行的,它们不会出现在内置对象的MRO ... – 2014-10-27 14:33:26

+1

什么都可以的迭代器。它不必从任何特定的基类型继承;它只需提供正确的方法。 – khelwood 2014-10-27 14:39:59

+0

Python不太重视对象是什么类型,它关心对象可以做什么。 – 2014-10-27 16:14:15

回答

4

Python中的任何内容都不会从IteratorIterable继承,因为它们体现了协议。 Python寻找__iter__ and __next__ methods,而不是针对特定的基类。任何对象都可以是迭代器或迭代器,只需实现这些方法即可。

zip()是C代码中定义的内置函数,它遵循所有内置函数的命名约定;这些总是小写;它返回的类型在这里并不完全相关,并且遵循函数名称。

collections.abc.Iterablecollections.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 
+1

有关'zip'而不是'Zip'的说明:这就是很多内置类型的工作方式; Python和标准库在一定程度上只符合PEP8。 – chepner 2014-10-27 14:52:05

+1

@chepner:PEP8指出应该尊重项目的当前约定,并且在CPython中,所有内置函数都是小写字母。所以'zip()'是大写的小写字母。 – 2014-10-27 14:54:42

+0

更重要的是,zip()返回的东西的实际类型是不相关的。没有人看过这门课。 zip()是小写字母,因为它用作函数。 – 2014-10-27 16:13:38