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

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

提交回复
热议问题