在将 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 类型会导致调用超类方法,但是也许我不完全理解为什么他们会将子类存储在接收者.class 属性中。