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

后端 未结 9 1958
甜味超标
甜味超标 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:22

    Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.

    In case the container is its own iterator, you can inherit from collections.Iterator. You only need to implement the next method then.

    An example is:

    >>> from collections import Iterator
    >>> class MyContainer(Iterator):
    ...     def __init__(self, *data):
    ...         self.data = list(data)
    ...     def next(self):
    ...         if not self.data:
    ...             raise StopIteration
    ...         return self.data.pop()
    ...         
    ...     
    ... 
    >>> c = MyContainer(1, "two", 3, 4.0)
    >>> for i in c:
    ...     print i
    ...     
    ... 
    4.0
    3
    two
    1
    

    While you are looking at the collections module, consider inheriting from Sequence, Mapping or another abstract base class if that is more appropriate. Here is an example for a Sequence subclass:

    >>> from collections import Sequence
    >>> class MyContainer(Sequence):
    ...     def __init__(self, *data):
    ...         self.data = list(data)
    ...     def __getitem__(self, index):
    ...         return self.data[index]
    ...     def __len__(self):
    ...         return len(self.data)
    ...         
    ...     
    ... 
    >>> c = MyContainer(1, "two", 3, 4.0)
    >>> for i in c:
    ...     print i
    ...     
    ... 
    1
    two
    3
    4.0
    

    NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.

提交回复
热议问题