Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这个python语法是什么意思?_Python_Generator_Yield - Fatal编程技术网

这个python语法是什么意思?

这个python语法是什么意思?,python,generator,yield,Python,Generator,Yield,我不是一个python爱好者,我正在努力理解一些python代码。我想知道下面最后一行代码是做什么的?是否返回了这种多个对象?或返回的3个对象的列表 req = SomeRequestBean() req.setXXX(xxx) req.YYY = int(yyy) device,resp,fault = yield req #<----- What does this mean ? req=SomeRequestBean() 请求设置xxx(xxx) req.YYY

我不是一个python爱好者,我正在努力理解一些python代码。我想知道下面最后一行代码是做什么的?是否返回了这种多个对象?或返回的3个对象的列表

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

device,resp,fault = yield req          #<----- What does this mean ?
req=SomeRequestBean()
请求设置xxx(xxx)
req.YYY=int(YYY)

device,resp,fault=yield req#最后一行是从显示代码所在的协同程序的
send
方法中解包一个元组

也就是说,它发生在函数中:

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

    device,resp,fault = yield req  
>>> 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
然后是客户端代码,在某个地方看起来像这样

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)
或者(稍微喜欢)


这里zip返回解包到
a
b
的元组。所以一个元组看起来像
('a',1)
,然后是
a=='a'
b==1
,这一行有两件事。更容易解释的是,
yield
语句返回的值是一个序列,因此逗号取序列的值并将其放入变量中,非常类似于以下内容:

>>> def func():
...     return (1,2,3)
...
>>> a,b,c = func()
>>> a
1
>>> b
2
>>> c
3
现在,使用
yield
语句可以返回多个值,而不仅仅是一个值,每次使用
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 coroutine(*args):
    yield None
    req = SomeRequestBean()
    req.setXXX(xxx)
    req.YYY = int(yyy)

    device,resp,fault = yield req  
>>> 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
以这种方式使用的发电机是