yield
Python中关键字的用途是什么?它有什么作用?
例如,我试图理解这段代码1:
def _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
Run Code Online (Sandbox Code Playgroud)
这是来电者:
result, candidates = [], [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
Run Code Online (Sandbox Code Playgroud)
_get_child_candidates
调用该方法时会发生什么?列表是否返回?单个元素?它又被召唤了吗?后续通话何时停止?
1.代码来自Jochen Schulz(jrschulz),他为度量空间创建了一个很棒的Python库.这是完整源代码的链接:模块mspace.
yield
在__iter__()
函数内部使用generator()有什么好处?通过阅读Python Cookbook后,我理解"如果你想让生成器向用户公开额外的状态,不要忘记你可以轻松地将它作为一个类实现,将生成器函数代码放在__iter__()
方法中."
import io
class playyield:
def __init__(self,fp):
self.completefp = fp
def __iter__(self):
for line in self.completefp:
if 'python' in line:
yield line
if __name__ =='__main__':
with io.open(r'K:\Data\somefile.txt','r') as fp:
playyieldobj = playyield(fp)
for i in playyieldobj:
print I
Run Code Online (Sandbox Code Playgroud)
问题:
yield
内部__iter__ ()
而不是使用单独的函数有yield
什么好处?