Return a non iterator from __iter__

后端 未结 4 1014
离开以前
离开以前 2021-01-03 14:14
class test(object):
    def __init__(self):
        pass
    def __iter__(self):
        return \"my string\"

o = test()
print iter(o)

Why does th

4条回答
  •  失恋的感觉
    2021-01-03 14:41

    The purpose of __iter__ magic function is to return something that you can iterate (e.g. loop) through. The most common solution is to return iter(something) where something could be a list, a tuple, set, dictionary, a string... anything that we can iterate through. Take a look at this example:

    class Band:
        def __init__(self):
            self.members = []
    
        def add_member(self, name):
            self.members.append(name)
    
        def __iter__(self):
            return iter(self.members)
    
    if __name__ == '__main__':
        band = Band()
        band.add_member('Peter')
        band.add_member('Paul')
        band.add_member('Mary')
    
        # Magic of __iter__:
        for member in band:
            print(member)
    

    Output:

    Peter
    Paul
    Mary
    

    In this case, the __iter__ magic function allows us to loop through band as if it is a collection of members. That means in your case, return "my string" will not do. If you want a list of chars in "my string":

    def __iter__(self):
        return iter("my string")  # ==> m, y, ' ', s, t, r, i, n, g
    

    However, if you want to return a list with a single element "my string", then:

    def __iter__(self):
        return iter(["my string"])
    

提交回复
热议问题