2

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

用例:

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

但这只是引发了“产生的未知对象”错误。

4

1 回答 1

0

我有可以启发你的代码片段:

片段1

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

片段2

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

片段3

for instance in Model.instantiator((yield motor_generator)):
  instance.attr = 'asdf'
于 2013-04-08T18:07:32.443 回答