少說話多寫程式碼之Python學習054——類的成員(生成器的方法和模擬生成器))
阿新 • • 發佈:2018-12-03
我們看看生成器的呼叫以及內部響應,
外部訪問生成器的send方法,類似於我們方位迭代器的next方法。
內部響應的過程是,yield作為表示式使用。生成器重新執行時,yield方法返回一個值,如果send方法被使用,則返回none。
比如這樣的過程,
def repeater(value): while True: new = (yield value) if new is not None : value = new r= repeater(42) print(r.__next__()) print(r.send('瞅你咋地!'))
輸出
42
瞅你咋地!
我們寫生成器時,還需要有兩個方法,throw和close。
throw丟擲異常,close方法停止生成器。對於,以前舊的程式碼不包含生成器的,我們需要模擬生成器,以相容程式。
這樣使用,
def myCommonFlatten(seq): result =[] try: try: seq+'' except TypeError:pass else:raise TypeError for list in seq: for item in myCommonFlatten(list): result.append(item) except TypeError:result.append(seq) return result strSeq=['張道陵',['葛玄',['薩守堅','許旌陽']]] for item in myCommonFlatten(strSeq): print(item)
輸出
張道陵
葛玄
薩守堅
許旌陽
工程檔案下載:https://download.csdn.net/download/yysyangyangyangshan/10823478