[英]python make class iterable by returning embedded iterable
我在python中有一個類,它有一個可迭代的實例變量。 我想通過迭代嵌入式迭代來迭代類的實例。
我實現如下:
def __iter__(self):
return self._iterable.__iter__()
我覺得在iterable上調用__iter__()
方法並不是很舒服,因為它是一種特殊的方法。 這是你如何在python中解決這個問題,還是有更優雅的解決方案?
委派__iter__
的“最佳”方式是:
def __iter__(self):
return iter(self._iterable)
或者,可能值得了解:
def __iter__(self):
for item in self._iterable:
yield item
哪個會讓你在返回之前擺弄每個項目(例如,如果你想要yield item * 2
)。
正如@Lattyware在評論中提到的那樣,PEP380(計划包含在Python 3.3中)將允許:
def __iter__(self):
yield from self._iterable
請注意,執行以下操作可能很誘人:
def __init__(self, iterable):
self.__iter__ = iterable.__iter__
但這不起作用 : iter(foo)
調用type(foo)
上的__iter__
方法,繞過foo.__iter__
。 例如,考慮一下:
class SurprisingIter(object):
def __init__(self):
self.__iter__ = lambda self: iter("abc")
def __iter__(self):
return iter([1, 2, 3])
你會期望該list(SurprisingIter())
將返回["a", "b", "c"]
,但它實際上返回[1, 2, 3]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.