这个Python语法是什么意思?
我不是一个Python爱好者,我想理解一些Python代码。我想知道下面代码的最后一行是做什么的?是那种返回多个对象的吗?或者返回 3 个对象的列表?
req = SomeRequestBean()
req.setXXX(xxx)
req.YYY = int(yyy)
device,resp,fault = yield req #<----- What does this mean ?
I am not a python guy and I am trying to understand some python code. I wonder what the last line of below code does? Is that kind of multiple objects returned? or list of 3 objects returned?
req = SomeRequestBean()
req.setXXX(xxx)
req.YYY = int(yyy)
device,resp,fault = yield req #<----- What does this mean ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这条线上发生了两件事。更容易解释的是,yield 语句返回一个序列值,因此逗号采用序列值并将它们放入变量中,就像这样:
现在, >yield 语句用于创建一个生成器,它可以返回多个值而不是一个,每次使用
yield
时返回一个值。例如:实际上,函数在
yield
语句处停止,等待被询问下一个值,然后再继续。在上面的示例中,
next()
从生成器获取下一个值。但是,如果我们使用send()
代替,我们可以将值发送回生成器,这些值由yield
语句返回到函数中:将这些放在一起,我们得到:
以这种方式使用的生成器称为协程。
There are two things going on in that line. The easier one to explain is that the
yield
statement is returning a value which is a sequence, so the commas take values of the sequence and put them in the variables, much like this:Now, the
yield
statement is used to create a generator, which can return a number of values rather than just one, returning one value each timeyield
is used. For example:In effect, the function stops at the
yield
statement, waiting to be asked for the next value before carrying on.In the example above
next()
gets the next value from the generator. However, if we usesend()
instead we can send values back to the generator which are returned by theyield
statement back in to the function:Putting this all together we get:
A generator used in this way is called a coroutine.
最后一行是从显示的代码所在的协程的
send
方法中解压一个元组。也就是说,它出现在一个函数中:
然后有一个客户端代码,在某个地方看起来有些东西像这样。
一个不涉及协程的更简单的例子是类似
or (稍微更花哨)
的东西,这里 zip 返回解压到
a
和b
的元组。因此一个元组看起来像('a', 1)
,然后是a == 'a'
和b == 1
。the last line is unpacking a tuple from the
send
method of the coroutine that the displayed code is located in.that is to say that it occurs in a function:
there is then client code that somewhere that looks something like this.
a simpler example of this that doesn't involve coroutines is something along the lines of
or (slightly fancier)
here zip returns tuples that get unpacked to
a
andb
. so one tuple would look like('a', 1)
and thena == 'a'
andb == 1
.