2010-09-14 174 views
6

我不是一個蟒蛇人,我想了解一些Python代碼。我想知道下面的代碼的最後一行是什麼?那種多個對象返回了嗎?或返回3個對象的列表?這個python語法是什麼意思?

req = SomeRequestBean() 
req.setXXX(xxx) 
req.YYY = int(yyy) 

device,resp,fault = yield req   #<----- What does this mean ? 

回答

9

該行有兩件事情正在進行。越容易一個解釋是,yield語句返回的值是一個序列,因此逗號取序列的值,並把它們的變量,就像這樣:

>>> def func(): 
...  return (1,2,3) 
... 
>>> a,b,c = func() 
>>> a 
1 
>>> b 
2 
>>> c 
3 

現在,yield聲明用於create a generator,它可以返回多個值而不是一個值,每次使用yield時返回一個值。例如:

>>> def func(): 
...  for a in ['one','two','three']: 
...   yield a 
... 
>>> g = func() 
>>> g.next() 
'one' 
>>> g.next() 
'two' 
>>> g.next() 
'three' 

實際上,功能停止在yield聲明,等着被要求攜帶之前的下一個值。

在上面的示例中,next()從生成器獲取下一個值。然而,如果我們使用send()相反,我們可以把值返回到它們由yield聲明回至該函數返回的發電機:

>>> def func(): 
...  total = 0 
...  while True: 
...  add = yield total 
...  total = total + add 
... 
>>> g = func() 
>>> g.next() 
0 
>>> g.send(10) 
10 
>>> g.send(15) 
25 

把所有這些組合起來,我們得到:

>>> def func(): 
...  total = 0 
...  while True: 
...   x,y = yield total 
...   total = total + (x * y) 
... 
>>> g = func() 
>>> g.next() 
0 
>>> g.send([6,7]) 
42 

一以這種方式使用的發電機是called a coroutine

4

的最後一行是由所顯示的代碼位於該協程的send方法拆包的元組

也就是說,它在函數發生:

def coroutine(*args): 
    yield None 
    req = SomeRequestBean() 
    req.setXXX(xxx) 
    req.YYY = int(yyy) 

    device,resp,fault = yield req 

然後有客戶端代碼,看起來像這樣的地方。

co = coroutine(*args) 
next(co) # consume the first value so we can start sending. 
co.send((device, resp, fault)) 

這不涉及協同程序一個簡單的例子是沿

a, b, c = (1, 2, 3) 

或(略票友)

for a, b in zip(['a', 'b'], [1, 2]): 
    print a, b 

這裏拉鍊返回元組獲取解壓東西線到ab。所以一個元組看起來像('a', 1),然後a == 'a'b == 1