yield的英文單字意思是生產,剛接觸Python的時候感到非常困惑,一直沒弄清楚yield的用法。
只是粗略的知道yield可以用來為一個函數返回值塞數據,例如下面的例子:
def addlist(alist): for i in alist: yield i + 1
然後透過呼叫取出每一項:
alist = [1, 2, 3, 4] for x in addlist(alist): print x,
這的確是yield應用的一個例子
1. 包含yield的函數
假如你看到某個函數包含了yield,這意味著這個函數已經是一個Generator,假如你看到某個函數包含了yield,這意味著這個函數已經是一個Generator,它的執行會和其他普通的函數有很多不同。例如下面的簡單的函數:
def h(): print 'To be brave' yield 5 h()
可以看到,呼叫h()之後,print 語句並沒有執行!這就是yield,那麼,要如何讓print 語句執行呢?這就是後面要討論的問題,透過後面的討論和學習,就會明白yield的工作原理了。
2. yield是一個表達式
Python2.5以前,yield是一個語句,但現在2.5中,yield是一個表達式(Expression),例如:
m = yield 5
)的回傳值將賦值給m,所以,認為m = 5 是錯誤的。那麼要如何取得(yield 5)的回傳值呢?需要用到後面要介紹的send(msg)方法。 3. 透過next()語句看原理現在,我們來揭曉yield的工作原理。我們知道,我們上面的h()被呼叫後並沒有執行,因為它有yield表達式,因此,我們透過next()語句讓它執行。 next()語句將還原Generator執行,並直到下一個yield表達式處。例如:def h(): print 'Wen Chuan' yield 5 print 'Fighting!' c = h() c.next()c.next()呼叫後,h()開始執行,直到遇到yield 5,因此輸出結果:Wen Chuan當我們再次呼叫c.next()時,會繼續執行,直到找到下一個yield表達式。由於後面沒有yield了,因此會拋出異常:Wen ChuanFighting!Traceback (most recent call last):
StopIteration
4. send(msg) 與next()
了解了next()如何讓包含yield的函數執行後,我們來看另一個非常重要的函數。 msg)。其實next()和send()在某個意義上作用是相似的,差別是send()可以傳遞yield表達式的值進去,而next()不能傳遞特定的值,只能傳遞None進去。因此,我們可以看做
c.next() 和 c.send(None) 作用是一樣的。
來看這個例子:
def h(): print 'Wen Chuan', m = yield 5 # Fighting! print m d = yield 12 print 'We are together!' c = h() c.next() #相当于c.send(None) c.send('Fighting!') #(yield 5)表达式被赋予了'Fighting!'
輸出的結果為:
Wen Chuan Fighting!
需要提醒的是,第一次呼叫時,請使用next()語句或是send(None),不能使用send發送一個非None的值,否則會出錯的,因為沒有yield語句來接收這個值。
5. send(msg) 與 next()的回傳值
send(msg) 和 next()是有回傳值的,它們的回傳值很特殊,回傳的是下一個yield表達式的參數。如yield 5,則回傳 5 。到這裡,是不是明白了什麼?本文第一個例子中,透過for i in alist 遍歷Generator,其實是每次都呼叫了alist.Next(),而每次alist.Next()的回傳值正是yield的參數,即我們開始認為被壓進去的東東。我們再延續上面的例子:
def h(): print 'Wen Chuan', m = yield 5 # Fighting! print m d = yield 12 print 'We are together!' c = h() m = c.next() #m 获取了yield 5 的参数值 5 d = c.send('Fighting!') #d 获取了yield 12 的参数值12 print 'We will never forget the date', m, '.', d
輸出結果:
Wen Chuan Fighting!
We will never forget the date 5 . 12中斷
ator靈活的技巧,可以透過throw拋出一個GeneratorExit異常來終止Generator。 Close()方法作用是一樣的,其實內部它是呼叫了throw(GeneratorExit)的。我們看:def close(self): try: self.throw(GeneratorExit) except (GeneratorExit, StopIteration): pass else: raise RuntimeError("generator ignored GeneratorExit") # Other exceptions are not caught因此,當我們呼叫了close()方法後,再呼叫next()或是send(msg)的話會拋出一個異常:
Traceback (most recent call last): File "/home/evergreen/Codes/yidld.py", line 14, in <module> d = c.send('Fighting!') #d 获取了yield 12 的参数值12 StopIteration

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中