程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

on python generator

編輯:Python

攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第5天,點擊查看活動詳情

0 環境

  • 編輯器:idea或vscode
  • 系統版本:windows10
  • python版本:3.9.6

1 前言

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.

2 生成器的定義

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方法調用它,會有值了.

3 初探yield和return

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.

4 總結

when I define a function,並且使用了yield關鍵, when we call the function,The returned object is a generator,然後for循環或next或者list(),Get the corresponding element.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved