Skip to main content
 首页 » 编程设计

python之从 __iter__ 返回一个非迭代器

2025年05月04日8wuhuacong

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__ 只返回字符串。何时以及为何检测到返回的对象不是迭代器对象?

请您参考如下方法:

可以通过添加 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'] 

最初错误的原因是 __iter__ 的 API 声称返回一个实际的迭代器。 iter() 函数检查以确保契约(Contract)得到履行。

请注意,这种错误检查也发生在其他地方。例如,len() 函数检查以确保 __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