How to implement __iter__(self) for a container object (Python)

后端 未结 9 1973
甜味超标
甜味超标 2020-12-02 08:00

I have written a custom container object.

According to this page, I need to implement this method on my object:

__iter__(self)

Howe

9条回答
  •  我在风中等你
    2020-12-02 08:18

    The "iterable interface" in python consists of two methods __next__() and __iter__(). The __next__ function is the most important, as it defines the iterator behavior - that is, the function determines what value should be returned next. The __iter__() method is used to reset the starting point of the iteration. Often, you will find that __iter__() can just return self when __init__() is used to set the starting point.

    See the following code for defining a Class Reverse which implements the "iterable interface" and defines an iterator over any instance from any sequence class. The __next__() method starts at the end of the sequence and returns values in reverse order of the sequence. Note that instances from a class implementing the "sequence interface" must define a __len__() and a __getitem__() method.

    class Reverse:
        """Iterator for looping over a sequence backwards."""
        def __init__(self, seq):
            self.data = seq
            self.index = len(seq)
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if self.index == 0:
                raise StopIteration
            self.index = self.index - 1
            return self.data[self.index]
    
    >>> rev = Reverse('spam')
    >>> next(rev)   # note no need to call iter()
    'm'
    >>> nums = Reverse(range(1,10))
    >>> next(nums)
    9
    

提交回复
热议问题