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

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

    In case you don't want to inherit from dict as others have suggested, here is direct answer to the question on how to implement __iter__ for a crude example of a custom dict:

    class Attribute:
        def __init__(self, key, value):
            self.key = key
            self.value = value
    
    class Node(collections.Mapping):
        def __init__(self):
            self.type  = ""
            self.attrs = [] # List of Attributes
    
        def __iter__(self):
            for attr in self.attrs:
                yield attr.key
    

    That uses a generator, which is well described here.

    Since we're inheriting from Mapping, you need to also implement __getitem__ and __len__:

        def __getitem__(self, key):
            for attr in self.attrs:
                if key == attr.key:
                    return attr.value
            raise KeyError
    
        def __len__(self):
            return len(self.attrs)
    

提交回复
热议问题