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

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

    example for inhert from dict, modify its iter, for example, skip key 2 when in for loop

    # method 1
    class Dict(dict):
        def __iter__(self):
            keys = self.keys()
            for i in keys:
                if i == 2:
                    continue
                yield i
    
    # method 2
    class Dict(dict):
        def __iter__(self):
            for i in super(Dict, self).__iter__():
                if i == 2:
                    continue
                yield i
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-02 08:35

    If your object contains a set of data you want to bind your object's iter to, you can cheat and do this:

    >>> class foo:
        def __init__(self, *params):
               self.data = params
        def __iter__(self):
            if hasattr(self.data[0], "__iter__"):
                return self.data[0].__iter__()
            return self.data.__iter__()
    >>> d=foo(6,7,3,8, "ads", 6)
    >>> for i in d:
        print i
    6
    7
    3
    8
    ads
    6
    
    0 讨论(0)
提交回复
热议问题