从__iter__返回一个非迭代器

问题描述

可以通过添加 iter() 调用来修复代码

class test(object):
    def __init__(self):
        pass
    def __iter__(self):
        return iter("my string")

这是一个示例运行:

>>> o = test()
>>> iter(o)
<iterator object at 0x106bfa490>
>>> list(o)
['m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g']

原始错误的原因是 的API声称要返回实际的迭代器。在 国际热核实验堆() 函数检查,以确保履行合同。

注意,这种错误检查也发生在其他地方。例如, len() 函数检查以确保 () 方法返回整数:

>>> class A:
        def __len__(self):
            return 'hello'

>>> len(A())
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    len(A())
TypeError: 'str' object cannot be interpreted as an integer

解决方法

class test(object):
    def __init__(self):
        pass
    def __iter__(self):
        return "my string"

o = test()
print iter(o)

为什么这会提供追溯?

$ python iter_implement.py
Traceback (most recent call last):
  File "iter_implement.py",line 9,in <module>
    print iter(o)
TypeError: iter() returned non-iterator of type 'str'

我希望__iter__在这种情况下只返回字符串。什么时候以及为什么检测到返回的对象不是迭代器对象?