Python __iter__和for循环

pyt*_*hor 3 python for-loop iterable

据我所知,我可以使用返回迭代器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)
Run Code Online (Sandbox Code Playgroud)

我有这个类的对象,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
...
>>>
Run Code Online (Sandbox Code Playgroud)

所以python看到a有一个__iter__方法,但不认为它是可迭代的.我做错了什么?这是python 2.6.4.

Gle*_*ard 12

有一个微妙的实现细节妨碍你:__iter__实际上不是一个实例方法,而是一个类方法.也就是说,obj.__class__.__iter__(obj)被称为,而不是obj.__iter__().

这是由于引擎优化,允许Python运行时更快地设置迭代器.这是必需的,因为迭代器尽可能快地非常重要.

无法__getattribute__为基础class类型定义,因此无法动态返回此方法.这适用于大多数__metamethods__; 你需要写一个实际的包装器.