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

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

    One option that might work for some cases is to make your custom class inherit from dict. This seems like a logical choice if it acts like a dict; maybe it should be a dict. This way, you get dict-like iteration for free.

    class MyDict(dict):
        def __init__(self, custom_attribute):
            self.bar = custom_attribute
    
    mydict = MyDict('Some name')
    mydict['a'] = 1
    mydict['b'] = 2
    
    print mydict.bar
    for k, v in mydict.items():
        print k, '=>', v
    

    Output:

    Some name
    a => 1
    b => 2
    

提交回复
热议问题