代码之家  ›  专栏  ›  技术社区  ›  Gopi

这个python语法是什么意思?

  •  6
  • Gopi  · 技术社区  · 14 年前

    我不是一个python人,我试图理解一些python代码。我想知道下面代码的最后一行是什么?是否返回了此类多个对象?或者返回3个对象的列表?

    req = SomeRequestBean()
    req.setXXX(xxx)
    req.YYY = int(yyy)
    
    device,resp,fault = yield req          #<----- What does this mean ?
    
    2 回复  |  直到 14 年前
        1
  •  9
  •   David Webb    14 年前

    这条线有两件事。更容易解释的是 yield 语句返回的值是一个序列,因此逗号接受序列的值并将其放入变量中,就像这样:

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

    现在, 产量 语句用于 create a generator ,它可以返回多个值而不是一个,每次返回一个值 产量 使用。例如:

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

    实际上,函数在 产量 声明,等待下一个值后再继续。

    在上面的例子中 next() 从生成器中获取下一个值。但是,如果我们使用 send() 相反,我们可以将值发送回由 产量 语句返回函数:

    >>> 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 .

        2
  •  4
  •   aaronasterling    14 年前

    最后一行是从 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
    

    这里zip返回解包到的元组 a b . 所以一个元组看起来像 ('a', 1) 然后 a == 'a' b == 1 .