简体   繁体   English

协程vs Python中的类

[英]coroutines vs classes in python

My question is a very broad one. 我的问题很广泛。 Why would one use coroutines when one can use objects? 当可以使用对象时,为什么要使用协程? I could easily implement an iterator that works only once under next() and after that you have to call o.send(x). 我可以轻松地实现一个在next()下仅工作一次的迭代器,然后您必须调用o.send(x)。 Is there something more to coroutines than state persistence that can be achieved via OOP? 除了通过OOP可以实现的状态持久化之外,协程还需要做更多的事情吗? Are they lighter? 他们更轻吗? Is it just syntactic sugar? 只是语法糖吗? I could actually ask the same about generators vs. iterators but there I think I have read that generators are simply syntactic sugar. 实际上,我可以对生成器与迭代器问相同的问题,但是我想我已经读到生成器只是语法糖。

If this is indeed the case, why are coroutines such a big deal? 如果确实如此,协程为何如此重要? I am sure I am missing something about them but I can't figure out what. 我确定我对他们有所遗漏,但我不知道是什么。

Yes, technically coroutines are syntactic sugar, but not the trivial kind. 是的,从技术上讲,协程是语法糖,但不是琐碎的糖。 Any coroutine can potentially be re-written manually without using yield , send , etc. However this transformation may be painful. 任何协程都可以在不使用yieldsend等的情况下手动进行重写。但是,这种转换可能很痛苦。 Consider (adapted from here ): 考虑(从此处改编):

def print_name(prefix):
  print("Searching prefix: {}".format(prefix))
  while True:
    firstName = (yield)
    lastName = (yield)
    if prefix in firstName or prefix in lastName:
      print("{} {}".format(firstName, lastName))

You could rewrite this as: 可以将其重写为:

class NamePrinter(object):
  def __init__(self, prefix):
    self.prefix = prefix
    self.gotFirstName = False

  def send(self, data):
    if not self.gotFirstName:
      self.firstName = data
      self.gotFirstName = True
    else:
      self.lastName = data
      if self.prefix in self.firstName or self.prefix in self.lastName:
        print(name)
      self.gotFirstName = False

This works. 这可行。 But even with this micro-example, we have to write a lot more when not using coroutines. 但是即使有了这个微型示例,当不使用协程时,我们也必须编写更多内容。 In more complex stateful coroutines the programmer would manually have to keep track of the current state, which variables are meaningful in the current state, etc. 在更复杂的有状态协程中,程序员将必须手动跟踪当前状态,哪些变量在当前状态中有意义等。

Coroutines in Python (and similarly async / await in modern JavaScript as well as future C++) automatically transform linear code into a state machine with well-controlled inputs, easy error handling, etc etc. Python中的协程(以及类似的现代JavaScript以及未来的C ++中的async / await )会自动将线性代码转换为具有良好控制的输入,易于处理的错误等的状态机。

Coroutines are a way to add asynchonous actions to your application. 协程是向应用程序添加异步动作的一种方式。 Objects are just simply things in your application that hold information or do work. 对象只是应用程序中保存信息或工作的事物。 So both are used together to create an asynchronous application. 因此,两者一起用于创建异步应用程序。

https://www.geeksforgeeks.org/coroutine-in-python/ https://www.geeksforgeeks.org/coroutine-in-python/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM