假设您使用了包装器对象:
class IterOrNotIter:
def __init__(self):
self.f = open('/tmp/toto.txt')
def __getattr__(self, item):
try:
return self.__getattribute__(item)
except AttributeError:
return self.f.__getattribute__(item)
此对象实现__iter__
,因为它将对它的任何调用传递给实现它的成员f
。一个很好的例子:
>>> x = IterOrNotIter()
>>> x.__iter__().__next__()
'Whatever was in /tmp/toto.txt\n'
根据文档(https://docs.python.org/3/library/stdtypes.html#iterator-types),IterOrNotIter因此应该是可迭代的。
但是,Python解释器无法将IterOrNotIter
对象识别为实际可迭代:
>>> x = IterOrNotIter()
>>> for l in x:
... print(l)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'IterOrNotIter' object is not iterable
虽然这有效:
>>> x = IterOrNotIter()
>>> for l in x.f:
... print(l)
...
Whatever was in /tmp/toto.txt
我不明白为什么。