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

python note generator

編輯:Python

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

0 環境

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

1 前言

前面簡單介紹了return和yield混用在一起,what will happen,下面繼續.

2 yield的原理

先定義個函數,它裡面有兩個yield,一個return.Results in our minds,would normally consider the lastreturn 3會被調用,讓我們debug一步步的debug下,驗證一下,What we guess right.

def gen2():
print("1")
yield 1
print(2)
yield 2
print(3)
return 3
if __name__ == '__main__':
result2 = gen2()
print(result2)
print(next(result2))
print(next(result2))
print(next(result2))
復制代碼

可以看到,這裡的gen2是個生成器.

Now execute the firstnext方法,進入了print("1").控制台打印結果是1.

繼續執行,進入到了yield 1. 在繼續執行,yield 1執行完後,回到__main__裡,第一個next得到yield彈出1的值,控制台也可以看到,Now ready to execute the secondnext方法了.

Now execute the secondnext方法,Once again into thegen2的函數中,it doesn't point to the firstprint("1"),而是繼續執行yield 1下一行的代碼,print("2"),也就說明,之前所講的,Protect the scene is very image.

繼續往下執行,得到了print的打印結果2. 再繼續往下執行,回到了__main__下的第三個next方法的位置,並得到了yield彈出值2. 繼續執行,Once again into thegen2函數中,指向print("3")這行代碼. 繼續執行,得到3的打印值. 繼續執行,得到報錯StopIteration: 3.

3 總結

There are two as aboveyield和一個return時,每當調用一次next方法時,into the function,and executed theyield,it will stop executing(不會往下執行,and stop here),then print out this timeyield彈出的值,當第二個next方法執行了,when entering the function,and the code is not executed from scratch,but from last timeyieldThe location is marked,Starting from its next line of code execution,Also illustrates the ready-made is preserved,當再次執行next方法時,There is no executable in the functionyield關鍵字了,會拋出異常,它的報錯StopIteration 3.Is the exception value thrown here?,返回值呢.假如再次next方法執行.規律就是,generator function function,它帶有yield語句的函數,The return value of a generator function is a generator.


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