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

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

    To answer the question about mappings: your provided __iter__ should iterate over the keys of the mapping. The following is a simple example that creates a mapping x -> x * x and works on Python3 extending the ABC mapping.

    import collections.abc
    
    class MyMap(collections.abc.Mapping):
        def __init__(self, n):
            self.n = n
    
        def __getitem__(self, key): # given a key, return it's value
            if 0 <= key < self.n:
                return key * key
            else:
                raise KeyError('Invalid key')
    
        def __iter__(self): # iterate over all keys
            for x in range(self.n):
                yield x
    
        def __len__(self):
            return self.n
    
    m = MyMap(5)
    for k, v in m.items():
        print(k, '->', v)
    # 0 -> 0
    # 1 -> 1
    # 2 -> 4
    # 3 -> 9
    # 4 -> 16
    

提交回复
热议问题