考虑以下代码:
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)
输出为:
x
4
5
6
y
1
2
3
我期望得到的输出结果:
y
1
2
3
y
1
2
3
iter()
(由for循环调用)如何工作,为什么它不调用已在构造函数中重写但对象的默认__iter__()
的对象__iter__()
?
编辑: 解决方法:
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)