攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第5天,點擊查看活動詳情
Although the previous article mentioned generators,For example, know the point generator comprehension or the generator analytic type,But what exactly does a generator look like,接觸過,但說不上來.Now let's meet the generator.
Generator keyword yield 來返回值,這種函數叫生成器函數,前面我們調用map函數時,will return us a generator object,它可以被for循環,to get each of these elements,It can also be a good indication that it is also an iterator in nature.
如下代碼:我定義了gen函數,每次for循環,使用關鍵字yield定義 --> yield item,If normal functions need itreturn,to get value,But it's not returning<generator object gen at 一串十六進制>
.它是可以使用next(result)調用,得到元素的.
def gen():
for item in range(8):
yield item
if __name__ == '__main__':
result = gen()
print(result)
print(next(result))
print(next(result))
復制代碼
我在用for循環result,結果如下.也就說yieldA value will pop up,Otherwise how would I know the result.This is different from ordinary functions,Ordinary functions are executed line by line,執行完了,就被銷毀了,但是這裡的yield不太一樣,The professional word is that it will remain live,這也說得通,為啥我用next方法調用它,會有值了.
Here we will be unnatural,拿yield和return比較,if they are mixed,returnUnder what circumstances,會有效,When will it be invalid,A simple conclusion first,當我們return在yield在下面,可以看作return是無效的,放在多yield的中間呢,如下圖,第二個next方法,在yield 1後面繼續執行,看到了return,Return directly to throw an exceptionStopIteration,It also explains the latteryieldis not available,你returnWrite more lateryieldAlso useless,Because the function has already aborted.
when I define a function,並且使用了yield關鍵, when we call the function,The returned object is a generator,然後for循環或next或者list(),Get the corresponding element.