我正在用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
这些字段是Object-class的一部分。但在我的代码中,字段也列在子类中,这是我想要避免的。我怎样才能做到这一点?我已经检查了super()函数,但我认为这不适合我的情况,因为我不想执行我想扩展它的方法。
干杯
-Luca。
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
答案 0 :(得分:2)
super()
可用于此目的。你可以在ObjectBoolean
:
def message_to_model(self, request):
super(ObjectBoolean, self).message_to_model(request)
if request.boolean:
self.current = request.boolean.success
self.target = request.boolean.target
为了实现这一点,Object
必须是一个新的样式类,如果polymodel.PolyModel
是一个新的样式类,那就是它。