相关疑难解决方法(0)

"yield"关键字有什么作用?

yieldPython中关键字的用途是什么?它有什么作用?

例如,我试图理解这段代码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.

python iterator yield generator coroutine

9664
推荐指数
46
解决办法
212万
查看次数

在__iter __()中使用yield有什么好处?

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)

问题:

  1. 额外的国家在这里意味着什么?
  2. 使用yield内部__iter__ ()而不是使用单独的函数有yield什么好处?

python yield-keyword

5
推荐指数
1
解决办法
1095
查看次数

标签 统计

python ×2

coroutine ×1

generator ×1

iterator ×1

yield ×1

yield-keyword ×1