python yield的終極解釋

(譯)Python關鍵字yield的解釋(stackoverflow):

http://stackoverflow.com/questions/231767/the-python-yield-keyword-explainedhtml

 

3.1. 提問者的問題

Python關鍵字yield的做用是什麼?用來幹什麼的?node

好比,我正在試圖理解下面的代碼:python

def node._get_child_candidates(self, distance, min_dist, max_dist):
    if self._leftchild and distance - max_dist < self._median:
        yield self._leftchild
    if self._rightchild and distance + max_dist >= self._median:
        yield self._rightchild

下面的是調用:ide

result, candidates = list(), [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance <= max_dist and distance >= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result 

當調用 _get_child_candidates 的時候發生了什麼?返回了一個列表?返回了一個元素?被重複調用了麼? 何時這個調用結束呢?函數

3.2. 回答部分

爲了理解什麼是 yield,你必須理解什麼是生成器。在理解生成器以前,讓咱們先走近迭代。oop

3.3. 可迭代對象

當你創建了一個列表,你能夠逐項地讀取這個列表,這叫作一個可迭代對象:post

>>> mylist = [1, 2, 3] >>> for i in mylist : ... print(i) 1 2 3 

mylist 是一個可迭代的對象。當你使用一個列表生成式來創建一個列表的時候,就創建了一個可迭代的對象:ui

>>> mylist = [x*x for x in range(3)] >>> for i in mylist : ... print(i) 0 1 4 

全部你可使用 for .. in .. 語法的叫作一個迭代器:列表,字符串,文件……你常用它們是由於你能夠如你所願的讀取其中的元素,可是你把全部的值都存儲到了內存中,若是你有大量數據的話這個方式並非你想要的。spa

3.4. 生成器

生成器是能夠迭代的,可是你 只能夠讀取它一次 ,由於它並不把全部的值放在內存中,它是實時地生成數據:code

>>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator : ... print(i) 0 1 4 

看起來除了把 [] 換成 () 外沒什麼不一樣。可是,你不能夠再次使用 for inmygenerator , 由於生成器只能被迭代一次:先計算出0,而後繼續計算1,而後計算4,一個跟一個的…

3.5. yield關鍵字

yield 是一個相似 return 的關鍵字,只是這個函數返回的是個生成器。

>>> def createGenerator() : ... mylist = range(3) ... for i in mylist : ... yield i*i ... >>> mygenerator = createGenerator() # create a generator >>> print(mygenerator) # mygenerator is an object! <generator object createGenerator at 0xb7555c34> >>> for i in mygenerator: ... print(i) 0 1 4 

這個例子沒什麼用途,可是它讓你知道,這個函數會返回一大批你只須要讀一次的值.

爲了精通 yield ,你必需要理解:當你調用這個函數的時候,函數內部的代碼並不立馬執行 ,這個函數只是返回一個生成器對象,這有點蹊蹺不是嗎。

那麼,函數內的代碼何時執行呢?當你使用for進行迭代的時候.

如今到了關鍵點了!

第一次迭代中你的函數會執行,從開始到達 yield 關鍵字,而後返回 yield 後的值做爲第一次迭代的返回值. 而後,每次執行這個函數都會繼續執行你在函數內部定義的那個循環的下一次,再返回那個值,直到沒有能夠返回的。

若是生成器內部沒有定義 yield 關鍵字,那麼這個生成器被認爲成空的。這種狀況可能由於是循環進行沒了,或者是沒有知足 if/else 條件。

3.6. 回到你的代碼

(譯者注:這是回答者對問題的具體解釋)

生成器:

# Here you create the method of the node object that will return the generator
def node._get_child_candidates(self, distance, min_dist, max_dist):

  # Here is the code that will be called each time you use the generator object :

  # If there is still a child of the node object on its left
  # AND if distance is ok, return the next child
  if self._leftchild and distance - max_dist < self._median:
            yield self._leftchild

  # If there is still a child of the node object on its right
  # AND if distance is ok, return the next child
  if self._rightchild and distance + max_dist >= self._median:
                yield self._rightchild

  # If the function arrives here, the generator will be considered empty
  # there is no more than two values : the left and the right children

調用者:

# Create an empty list and a list with the current object reference
result, candidates = list(), [self] # Loop on candidates (they contain only one element at the beginning) while candidates: # Get the last candidate and remove it from the list node = candidates.pop() # Get the distance between obj and the candidate distance = node._get_dist(obj) # If distance is ok, then you can fill the result if distance <= max_dist and distance >= min_dist: result.extend(node._values) # Add the children of the candidate in the candidates list # so the loop will keep running until it will have looked # at all the children of the children of the children, etc. of the candidate candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result 

這個代碼包含了幾個小部分:

  • 咱們對一個列表進行迭代,可是迭代中列表還在不斷的擴展。它是一個迭代這些嵌套的數據的簡潔方式,即便這樣有點危險,由於可能致使無限迭代。candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 窮盡了生成器的全部值,但 while 不斷地在產生新的生成器,它們會產生和上一次不同的值,既然沒有做用到同一個節點上.
  • extend() 是一個迭代器方法,做用於迭代器,並把參數追加到迭代器的後面。

一般咱們傳給它一個列表參數:

>>> a = [1, 2] >>> b = [3, 4] >>> a.extend(b) >>> print(a) [1, 2, 3, 4] 

可是在你的代碼中的是一個生成器,這是不錯的,由於:

  • 你沒必要讀兩次全部的值
  • 你能夠有不少子對象,但沒必要叫他們都存儲在內存裏面。

而且這很奏效,由於Python不關心一個方法的參數是否是個列表。Python只但願它是個能夠迭代的,因此這個參數能夠是列表,元組,字符串,生成器... 這叫作 ducktyping,這也是爲什麼Python如此棒的緣由之一,但這已是另一個問題了...

你能夠在這裏停下,來看看生成器的一些高級用法:

3.7. 控制生成器的窮盡

>>> class Bank(): # let's create a bank, building ATMs ... crisis = False ... def create_atm(self) : ... while not self.crisis : ... yield "$100" >>> hsbc = Bank() # when everything's ok the ATM gives you as much as you want >>> corner_street_atm = hsbc.create_atm() >>> print(corner_street_atm.next()) $100 >>> print(corner_street_atm.next()) $100 >>> print([corner_street_atm.next() for cash in range(5)]) ['$100', '$100', '$100', '$100', '$100'] >>> hsbc.crisis = True # crisis is coming, no more money! >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> wall_street_atm = hsbc.create_atm() # it's even true for new ATMs >>> print(wall_street_atm.next()) <type 'exceptions.StopIteration'> >>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty >>> print(corner_street_atm.next()) <type 'exceptions.StopIteration'> >>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business >>> for cash in brand_new_atm : ... print cash $100 $100 $100 $100 $100 $100 $100 $100 $100 ... 

對於控制一些資源的訪問來講這頗有用。

3.8. Itertools,你最好的朋友

itertools包含了不少特殊的迭代方法。是否是曾想過複製一個迭代器?串聯兩個迭代器?把嵌套的列表分組?不用創造一個新的列表的 zip/map?

只要 import itertools

須要個例子?讓咱們看看比賽中4匹馬可能到達終點的前後順序的可能狀況:

>>> horses = [1, 2, 3, 4] >>> races = itertools.permutations(horses) >>> print(races) <itertools.permutations object at 0xb754f1dc> >>> print(list(itertools.permutations(horses))) [(1, 2, 3, 4),  (1, 2, 4, 3),  (1, 3, 2, 4),  (1, 3, 4, 2),  (1, 4, 2, 3),  (1, 4, 3, 2),  (2, 1, 3, 4),  (2, 1, 4, 3),  (2, 3, 1, 4),  (2, 3, 4, 1),  (2, 4, 1, 3),  (2, 4, 3, 1),  (3, 1, 2, 4),  (3, 1, 4, 2),  (3, 2, 1, 4),  (3, 2, 4, 1),  (3, 4, 1, 2),  (3, 4, 2, 1),  (4, 1, 2, 3),  (4, 1, 3, 2),  (4, 2, 1, 3),  (4, 2, 3, 1),  (4, 3, 1, 2),  (4, 3, 2, 1)] 

3.9. 瞭解迭代器的內部機理

迭代是一個實現可迭代對象(實現的是 __iter__() 方法)和迭代器(實現的是 __next__()方法)的過程。可迭代對象是你能夠從其獲取到一個迭代器的任一對象。迭代器是那些容許你迭代可迭代對象的對象。

更多見這個文章 http://effbot.org/zone/python-for-statement.htm

 

 

for 等迭代器的特性:

將全部數據一次性的返回給調用者,第二次調用仍是一次性的返回相同的數據(不多有不一樣的狀況,若是初始參數同樣,基本就是每次調用返回的數據都相同)

yield 等生成器的特性:

一、它只是返回一個迭代協議(迭代原則,迭代規則,迭代方法,隨你怎麼想)

二、當你一次調用yield的next(),它只返回一個值,就是當前yield(的值)

三、下次調用yield的next()會從步驟2繼續執行,直到遇到下一個yield,而後返回該yield(的值)

四、若是期間步驟二、3任什麼時候候返回的不是yield,則整個yield結束(yield被丟棄了),之後無論你怎麼調用next(準確的說,next不存在了,由於yield都沒了)

示例:

def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print item
相關文章
相關標籤/搜索