私が理解しているように、反復子を返すメソッドを使用for
して、オブジェクトに対してループ構造を使用できます。__iter__
次の__getattribute__
メソッドを実装するオブジェクトがあります。
def __getattribute__(self,name):
if name in ["read","readlines","readline","seek","__iter__","closed","fileno","flush","mode","tell","truncate","write","writelines","xreadlines"]:
return getattr(self.file,name)
return object.__getattribute__(self,name)
このクラスのオブジェクトがa
あり、次のことが起こります。
>>> hasattr(a,"__iter__")
True
>>> for l in a: print l
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'TmpFile' object is not iterable
>>> for l in a.file: print l
...
>>>
そのため、 Python はa
メソッドがあることを認識して__iter__
いますが、反復可能であるとは考えていません。私は何を間違えましたか?これはpython 2.6.4です。