python - __builtin__.iterator 不存在?

标签 python python-2.7 cpython

考虑:

Python 2.7.3 (default, Aug  2 2012, 16:55:39) 
[GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import __builtin__
>>> type(iter('123'))
<type 'iterator'>
>>> type(iter('123')).__class__
<type 'type'>
>>> type(iter('123')).__name__
'iterator'
>>> type(iter('123')).__module__
'__builtin__'
>>> __builtin__.iterator
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'iterator'
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
>>> 

__builtin__.iterator 是否真的存在?是否有适当的方法来获取对该类的引用,而无需使用 iter 创建随机数实例?

最佳答案

并非所有内部对象类型都列在 __builtin__ 结构中,没有。

您在那里也找不到方法类型,也找不到生成器类型或许多其他类型。该命名空间中仅列出您在 Python 代码中实际使用的名称。

types module 中列出了一些此类类型,但迭代器类型不是,因为,如 source states :

# Iterators in Python aren't a matter of type but of protocol.  A large
# and changing number of builtin types implement *some* flavor of
# iterator.  Don't check the type!  Use hasattr to check for both
# "__iter__" and "next" attributes instead.

如果您想测试某物是否是迭代器,请使用 Iterator ABC相反:

import collections

if isinstance(something, collections.Iterator):

如果您需要获取字符串返回的iterator类型,您可以使用type():

>>> type(iter('123'))
<type 'iterator'>

并存储它;这就是 types 模块生成许多引用的方式。

但是,请知道该类型不是通用的:

>>> iterator = type(iter(''))
>>> isinstance(iter([]), iterator)
False
>>> iter([])
<listiterator object at 0x108e72d50>
>>> isinstance(reversed([]), iterator)
False
>>> reversed([])
<listreverseiterator object at 0x108e72d50>

但是使用 ABC 进行的测试确实可以识别所有这些:

>>> from collections import Iterator
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter(reversed([])), Iterator)
True
>>> isinstance(iter(''), Iterator)
True

如果您需要创建一个迭代器,那么要么生成一个序列并返回 iter() 的结果,要么自己生成一个迭代器类型。后者很简单,要么使用生成器表达式,使用 __iter__ 的生成器函数,或者为您的类型提供一个 __next__ 方法,每次调用该方法时都会生成一个项目(并且让__iter__返回self)。

关于python - __builtin__.iterator 不存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25612946/

相关文章:

python : Testing Video in OpenCV using python

python - list() 使用比列表理解稍多的内存

python - 从另一个对象访问结构指针时遇到问题

python - 绘图中的 3d 和 2d 子图

python - Pip 错误,OSError Errno 22 参数无效

python - 在另一个目录的脚本中运行时,Pyclbr readmodule 失败

python - 属性名称是否在 python 中基于实例消耗内存

python - Pandas:使用 group by,将多个列值组合为 groupby 中的一个不同组

python - 如何更改 Linux 上 Python 的默认版本以便安装和使用某些模块?

python - 嵌套的 Pandas 数据框 - 如何按数据选择/分组?