gpt4 book ai didi

python - __builtin__.iterator 不存在?

转载 作者:行者123 更新时间:2023-12-01 05:03:09 26 4
gpt4 key购买 nike

考虑:

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/

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