Consider the following code:
class A:
def __init__(self):
def do():
print("y")
return iter([1,2,3])
self.__iter__ = do
def __iter__(self):
print("x")
return iter([4,5,6])
for x in A():
print(x)
for x in A().__iter__():
print(x)
The output is:
x
4
5
6
y
1
2
3
What I would expect as an output:
y
1
2
3
y
1
2
3
How does iter()
(which is called by the for loop) work and why does it not call the object's __iter__()
that has been overridden in the constructor but the classes' default __iter__()
?
Edit: Workaround:
class A:
def __init__(self):
def do():
print("y")
return iter([1,2,3])
self.it = do
def __iter__(self):
return self.it()
for x in A():
print(x)
for x in A().__iter__():
print(x)