Search code examples
pythonpython-2.7iterationinstanceself

How can an instance be iterated over?


In datatstructures.py, there is a method values():

def values(self):
    """Iterate over all values."""
    for item in self:
        yield item[0]

self is an instance of the class; how can it be iterated over?


Solution

  • Simple, it has to implement __iter__ method, e.g.

    class Test:
        def __iter__(self):
            yield 1
            yield 2
    
    >>> instance = Test()
    >>> for val in instance:
    ...     print val
    ...
    1
    2