開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のIII部(ステートメント)13章(whileループとforループ)3を解いてみる。
3.
ビルトイン関数のiterが自動的に呼び出されて、__next__メソッドを持つ反復処理に対応したオブジェクトが戻され、逐一nextメソッドが呼び出される。(StopItrationエラーが発生して終了)
コード(TextWrangler)
sample.py
#!/usr/bin/env python #encoding: utf-8 L = [1,2,3,4,5]; print("forループ") for x in L: print(x) print("__next__メソッドを使用") I = iter(L) print(I.__next__()) print(I.__next__()) print(I.__next__()) print(I.__next__()) print(I.__next__()) try: I.__next__() except StopIteration: print("StopIterationエラー発生") except: print("エラー") finally: print("終了")
入出力結果(Terminal)
$ ./sample.py forループ 1 2 3 4 5 __next__メソッドを使用 1 2 3 4 5 StopIterationエラー発生 終了 $
0 コメント:
コメントを投稿