class test(object):
def __init__(self):
pass
def __iter__(self):
return \"my string\"
o = test()
print iter(o)
Why does th
The code can be repaired by adding an iter() call:
class test(object):
def __init__(self):
pass
def __iter__(self):
return iter("my string")
Here is a sample run:
>>> o = test()
>>> iter(o)
>>> list(o)
['m', 'y', ' ', 's', 't', 'r', 'i', 'n', 'g']
The reason for the original error is that the API for __iter__ purports to return an actual iterator. The iter() function checks to make sure the contract is fulfilled.
Note, this kind of error checking occurs in other places as well. For example, the len() function checks to make sure a __len__() method returns an integer:
>>> class A:
def __len__(self):
return 'hello'
>>> len(A())
Traceback (most recent call last):
File "", line 1, in
len(A())
TypeError: 'str' object cannot be interpreted as an integer