我正在用 Python 编写一个 Google Appengine 应用程序。该应用程序确实通过谷歌云端点消息接收和发送数据。您将在下面找到数据库模型定义的示例。Object 包含所有对象,ObjectBoolean 只是布尔对象,ObjectInteger 只是整数对象。所有的类都定义了两个方法:message_to_model() 和 model_to_message()。
如何重用子类中的方法?我确实想摆脱重复的代码,例如:
self.name = request.name
self.description = request.description
self.created = request.created
self.modified = request.modified
这些字段是对象类的一部分。但是在我的代码中,这些字段也列在子类中,这是我想要避免的。我怎样才能做到这一点?我确实已经检查了 super() 函数,但我认为这不适合我的情况,因为我不想执行我想要扩展它的方法。
干杯
-卢卡。
from google.appengine.ext.ndb import polymodel
from google.appengine.ext import ndb
from endpoint_messages.object import *
class Object(polymodel.PolyModel):
name = ndb.StringProperty(required=True, verbose_name="Name")
description = ndb.TextProperty(verbose_name="Description")
created = ndb.DateTimeProperty(auto_now_add=True, verbose_name="Created")
modified = ndb.DateTimeProperty(auto_now=True, verbose_name="Modified")
def model_to_message(self):
return ObjectResponseMessage(class_name=self._class_name(),
id=self.key.integer_id(),
name=self.name,
description=self.description,
created=self.created,
modified=self.modified)
def message_to_model(self, request):
self.name = request.name
self.description = request.description
self.created = request.created
self.modified = request.modified
class ObjectBoolean(Object):
current = ndb.BooleanProperty(verbose_name="Current")
target = ndb.BooleanProperty(verbose_name="Target")
def model_to_message(self):
return ObjectResponseMessage(class_name=self._class_name(),
id=self.key.integer_id(),
name=self.name,
description=self.description,
created=self.created,
modified=self.modified,
boolean=ObjectBooleanMessage(current=self.current,
target=self.target))
def message_to_model(self, request):
self.name = request.name
self.description = request.description
self.created = request.created
self.modified = request.modified
if request.boolean:
self.current = request.boolean.success
self.target = request.boolean.target
class ObjectInteger(Object):
current = ndb.IntegerProperty(verbose_name="Current")
target = ndb.IntegerProperty(verbose_name="Target")
def model_to_message(self):
return ObjectResponseMessage(class_name=self._class_name(),
id=self.key.integer_id(),
name=self.name,
description=self.description,
created=self.created,
modified=self.modified,
float=ObjectIntegerMessage(current=self.current,
target=self.target))
def message_to_model(self, request):
self.name = request.name
self.description = request.description
self.created = request.created
self.modified = request.modified
if request.integer:
self.current = request.integer.current
self.target = request.integer.target