python yield from 語法
yield語法比較簡單, 教程也很多 , yield from的中文講解很少 , python官網是這樣解釋的
PEP 380 adds the yield from expression, allowing a generator to delegate part of its operations to another generator. This allows a section of code containing yield to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.
大意是說 yield from 表達式允許一個生成器代理另一個生成器, 這樣就允許生成器被替換為另一個生成器, 子生成器允許返回值
def g1(x):
yield range(x)
def g2(x):
yield from range(x)
it1 = g1(5)
it2 = g2(5)
print( [ x for x in it1] )
#out [range(0, 5)]
print( [ x for x in it2] )
#out [0, 1, 2, 3, 4]
可以看到 , yield返回一個生成器 , 這個生成器就是range自身 , yield from 也返回一個生成器, 這個生成器是由range代理的
yield from 在遞歸結構中常用 , 例如
class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
如果不加上from , depth_first 只能返回根節點的值