管道发电机在一起

时间:2013-04-08 00:56:51

标签: python python-2.7 iterator generator tornado-motor

我可以访问通过motor Mongo适配器从数据库中产生属性哈希的生成器:

for attrs in (yield motor_generator):
  print attrs

我正在尝试创建一个类方法,如果给定一个生成器,可以实例化自身的实例,但不完全确定如何去做。我有:

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    (self(attrs) for attrs in (yield motor_generator))

USECASE:

for instance in Model.instantiator(motor_generator):
  instance.attr = 'asdf'

但这只是提出了一个“屈服于未知对象”的错误。

1 个答案:

答案 0 :(得分:0)

我有能够启发你的代码片段:

snippet1

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    # you can not put the yield here. it will transform this function into a generator.
    return map(self, motor_generator) # map is lazy in python 3

snippet2

class Model:
  @classmethod
  def instantiator(self, motor_generator):
    attrss = motor_generator # I put this outside because i fear a syntax misunderstanding with generators
    return [self(attrs) for attrs in attrss] # with round brackets it would be evaluated on demand = in the for loop but not in this method

snippet3

for instance in Model.instantiator((yield motor_generator)):
  instance.attr = 'asdf'