在Python中使用协程。如何链接两个协程

时间:2019-10-02 09:49:19

标签: python-3.x coroutine

我正在运行两个协程函数,但未获得所需的输出。任何帮助表示赞赏。下面是代码。

def coroutine_decorator(coroutine_func):
    def wrapper(*x,**y):
        c = coroutine_func(*x,**y)
        next(c)
        return c
    return wrapper


@coroutine_decorator
def linear_equation(a, b):
    x=yield
    c=a*(x**2)+b
    print("Expression, {}*x^2 + {}, with x being {} equals {}".format(a,b,x,c))


@coroutine_decorator
def numberParser():
    y=yield
    equation1 = linear_equation(3, 4)
    equation2 = linear_equation(2, -1)
    equation1.send(y)
    equation2.send(y)




def main(x):
    n = numberParser()
    n.send(x)
    n.close()

if __name__ == '__main__':

    main(6)

attaching image for expected output, my current output and the error

1 个答案:

答案 0 :(得分:0)

您的代码:

def numberParser():
    y=yield
    equation1 = linear_equation(3, 4)
    equation2 = linear_equation(2, -1)
    equation1.send(y)
    equation2.send(y)

更改为以下代码

def numberParser():
   while True: 
        y=yield
        equation1 = linear_equation(3, 4)
        equation2 = linear_equation(2, -1)
        equation1.send(y)
        equation2.send(y)

由于收益率值因缺少一段时间而变为“ None”而出现错误