資料內容:
Python中關鍵字yield有什么作用?
yield有什么用?
例如下面這段代碼:
def node._get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
下面是調用它:
result, candidates = list(), [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
當 _get_child_candidates 方法被調用的時候發(fā)生了什么?是返回一個列表?還是一個元祖?它
還能第二次調用嗎?后面的調用什么時候結束?
為了理解yield有什么用,首先得理解generators,而理解generators前還要理解iterables