據我所知,我可以在__iter__
方法的對象上使用for
循環構造,該方法返回一個迭代器。我有我實現以下__getattribute__
方法的對象:Python __iter__和for循環
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。
+1所以這就是爲什麼'iter'不叫'__getattribute__' ...正如他們所說,你每天都會在SO上學到新東西:) – delnan 2011-03-14 16:13:00
+1和delnan說的。 – slezica 2011-03-14 16:19:13
請注意,您可以看到此副作用(至少在CPython中):如果您定義了__getattribute__,那麼當您使用iter時會注意到它會被調用爲__class__,因爲運行時會查找要調用'__iter__'的對象的類。 (這應該被認爲是一個實現細節。) – 2011-03-14 16:58:20