Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
PythonのYieldを
かじってみた
@24motz
2014-05-03 LT駆動開発03
Pythonの関数
Python 2.7.6 (default, Nov 18 2013, 15:12:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
T...
yieldを含む関数
>>> def hoge():
... yield
...
>>> type(hoge)
<type 'function'>
>>> hoge()
<generator object hoge at 0x1019fda00...
イテレーター
>>> def hoge():
... yield 'a'
... yield 'b'
...
>>> g = hoge()
>>> print g.next()
a
>>> print g.next()
b
>>> print ...
シーケンス生成
>>> def hoge():
... yield 'a'
... yield 'b'
...
>>> g = hoge()
>>> for i in g:
... print i
...
a
b
sendメソッド
>>> def hoge():
... s = (yield 'a')
... s = (yield s + 'b')
... s = (yield s + 'c')
...
>>> g = hoge()
>>> print ...
状態遷移モデル
def stateManagerGenerator():
while True:
ev = (yield State.FIRST)
if ev == Event.GOTO_SECOND:
break
while True:
ev...
Upcoming SlideShare
Loading in …5
×

Python yield

3,232 views

Published on

Python の Yield をかじってみた
LT駆動開発03

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Python yield

  1. 1. PythonのYieldを かじってみた @24motz 2014-05-03 LT駆動開発03
  2. 2. Pythonの関数 Python 2.7.6 (default, Nov 18 2013, 15:12:51) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. ! >>> def a(): ... print "hello" ... >>> a() hello >>> type(a) <type 'function'>
  3. 3. yieldを含む関数 >>> def hoge(): ... yield ... >>> type(hoge) <type 'function'> >>> hoge() <generator object hoge at 0x1019fda00> >>> g = hoge() >>> type(g) <type 'generator'> ! yieldを含む関数は
 イテレータと同じインタフェースを持つ 呼び出し可能オブジェクト (ジェネレーター)を返す
  4. 4. イテレーター >>> def hoge(): ... yield 'a' ... yield 'b' ... >>> g = hoge() >>> print g.next() a >>> print g.next() b >>> print g.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
  5. 5. シーケンス生成 >>> def hoge(): ... yield 'a' ... yield 'b' ... >>> g = hoge() >>> for i in g: ... print i ... a b
  6. 6. sendメソッド >>> def hoge(): ... s = (yield 'a') ... s = (yield s + 'b') ... s = (yield s + 'c') ... >>> g = hoge() >>> print g.send(None) a >>> print g.send('x') xb >>> print g.send('y') yc >>> print g.send('z') Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration 呼出し側からジェネレータに
 値を渡すことができる ただし 最初の呼び出しは値を渡せない ! send(None) は next() でも可 最初だけnext()なのは気持ち悪い
  7. 7. 状態遷移モデル def stateManagerGenerator(): while True: ev = (yield State.FIRST) if ev == Event.GOTO_SECOND: break while True: ev = (yield State.SECOND) if ev == Event.GOTO_END: break while True: ev = (yield State.END) ! sm = stateManagerGenerator() state = sm.send(None) #=> FIRST state = sm.send(Event.DUMMY) #=> FIRST state = sm.send(Event.GOTO_SECOND) #=> SECOND 受け取ったevに応じて 次の状態に進む 状態遷移の規則を ひとつの関数に まとめられる

×