Return a non iterator from __iter__

后端 未结 4 991
离开以前
离开以前 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:33

    To answer your specific question. Python2 appears to check for the presence of a .next class attribute:

    >>> class test(object):
    ...     next = None
    ...     def __iter__(self):
    ...         return self
    ... 
    >>> print iter(test())
    <__main__.test object at 0x7fcef75c2f50>
    

    An instance attribute won't do:

    >>> class test(object):
    ...    def __init__(self):
    ...        self.next = None
    ...    def __iter__(self):
    ...        return self
    ... 
    >>> print iter(test())
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: iter() returned non-iterator of type 'test'
    

提交回复
热议问题