Return a non iterator from __iter__

后端 未结 4 1030
离开以前
离开以前 2021-01-03 14:14
class test(object):
    def __init__(self):
        pass
    def __iter__(self):
        return \"my string\"

o = test()
print iter(o)

Why does th

4条回答
  •  孤独总比滥情好
    2021-01-03 14:24

    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
    

提交回复
热议问题