Python __iter__和for循环 [英] Python __iter__ and for loops
问题描述
据我所知,我可以在 __ iter __
方法上使用来构建一个迭代器。我有一个对象为我实现以下
__ getattribute __
方法:
def __getattribute __(self,name):
如果名称是[read,readlines,readline,seek,__ iter __, (),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(最近一次调用的最后一个):
在< module>中的第1行创建< stdin>
TypeError:'TmpFile'对象不可迭代
>>> for l in a.file:print l
...
>>>
所以python看到 a
有一个 __ iter __
方法,但不认为它是可迭代的。我做错了什么?这是与Python 2.6.4。
有一个微妙的实现细节得到你的方式: __ iter__
实际上不是一个实例方法,而是一个类方法。也就是说,调用 obj .__ class __.__ iter __(obj)
,而不是 obj .__ iter __()
p>
这是由于插槽下的插槽优化造成的,允许Python运行时更快地设置迭代器。这是必须的,因为迭代器要尽可能快是非常重要的。
不可能为 __ getattribute __
定义底层的类
类型,所以不可能动态地返回这个方法。这适用于大多数 __ metamethods __
;你需要写一个实际的包装。
As I understand it, I can use the for
loop construction on an object with a __iter__
method that returns an iterator. I have an object for which I implement the following __getattribute__
method:
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)
I have an object of this class, a
for which the following happens:
>>> 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
...
>>>
So python sees that a
has an __iter__
method, but doesn't think it is iterable. What have I done wrong? This is with python 2.6.4.
There's a subtle implementation detail getting in your way: __iter__
isn't actually an instance method, but a class method. That is, obj.__class__.__iter__(obj)
is called, rather than obj.__iter__()
.
This is due to slots optimizations under the hood, allowing the Python runtime to set up iterators faster. This is needed since it's very important that iterators be as fast as possible.
It's not possible to define __getattribute__
for the underlying class
type, so it's not possible to return this method dynamically. This applies to most __metamethods__
; you'll need to write an actual wrapper.
这篇关于Python __iter__和for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!