class test(object):
def __init__(self):
pass
def __iter__(self):
return \"my string\"
o = test()
print iter(o)
Why does th
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"])