在将 ndb.Polymodel 超类存储为 ndb.StructuredProperty 时,我无法访问子类方法;相反,调用超类方法并引发 NotImplementedError。这是我想要完成的任务的删节版本。
class Recipient(polymodel.PolyModel):
name = ndb.StringProperty()
def PrettyPrinting(self):
raise NotImplementedError, 'Rawr'
class ShippingRecipient(Recipient):
address_line_one = ndb.StringProperty()
#there are other properties, but they aren't necessary here.
def PrettyPrinting(self):
return 'Hey, this should be called.'
class LocalRecipient(Recipient):
distribution_location = ndb.StringProperty()
#same deal, more attributes, but useless for this example.
def PrettyPrinting(self):
return 'Hey this should be called.'
class Shipment(ndb.Model):
recipient = ndb.StructuredProperty(Recipient)
现在假设我已保存货件并将 ShippingRecipient 存储到货件的收件人字段中。在数据存储中,货件收件人.class == ['Recipient', 'ShippingRecipient']。当我打电话时:
shipment = Shipment.get_by_id('some_key')
shipment.recipient.PrettyPrinting()
引发 NotImplementedError,而不是 PrettyPrinting(...) 的 ShippingRecipient 实现。我希望在访问货件的收件人字段时调用子类方法。有没有办法可以改为使用子类方法?我知道说结构化属性的类型为 Recipient 会导致调用超类方法,但也许我不完全理解为什么他们会将子类存储在recipient.class 属性中。
我不相信这行得通。它只会存储 Recipient 实例。
如果您查看 PolyModel 的工作原理,您会发现所有变体都存储为基类,
在你的例子中Recipient
。它还存储子类名称,当从数据存储中检索实体时,它会重新创建特定的子类。
我真的怀疑他们是否会将这种机制构建到 StructuredProperty 实例化中,而您已经发现情况确实如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)