How ugly is my code that implements polymorphic models?

I am using Polymorphic models .

Simple question: my code below works without using this line below that I see in other people's code. What should he do?

#super(GeneralModel, self).__init__(*args, **kwargs)

      

Merciless question: I have a feeling that my code below, although it works, is not the nicest option.

A short summary of what I am doing: I am creating (or creating) a new datastore model object based on a "impure" JSON object sent to the server. 1st I want to do some generic input cleanup specified in the generic (or super) model and then do some special methods that are specified in each special (or subclass) model as def parse

.

class GeneralModel(polymodel.PolyModel):
 lat_long_list = db.ListProperty(db.GeoPt)
 zooms = db.ListProperty(int)

     def __init__(self, *args, **kwargs):
  self.lat_long_list = [ db.GeoPt( pt[0] , pt[1] ) for pt in zip( kwargs["lat"] , kwargs["lon"] ) ]
  del kwargs["lat"]
  del kwargs["lon"]
  if "zooms" not in kwargs: kwargs["zooms"] = ZOOMS # some default
  for property,value in kwargs.items():
   setattr(self,property,value)
  #super(NamedModel, self).__init__(*args, **kwargs)
  self.parse()

 def parse(self):
         raise NotImplementedError('Need to define this for each category')


class SpecialModel(GeneralModel):
 stringText = db.StringProperty()
 words_list = db.StringListProperty()

 def parse( self ):
  self.words_list = self.stringText.split(",")  

      

This is how I check if my code is working:

>>>kwargs={'stringText':'boris,ted','lat':[0,1,2,3],'lon':[0,1,2,8],'zooms':[0,10]}
>>>entity=SpecialModel(key_name="tester",**kwargs)
>>>entity.words_list
['boris', 'ted']

      

+2


a source to share


1 answer


The 'super' line calls the parent object's constructor. If you don't include it, the parent constructor will not be called and your model will not be initialized correctly. You should, in effect, call it first, before any of your own initialization.

However, overriding the constructor on models is strongly discouraged. The constructor is not just used when you call it, but also by the system to create instances that are loaded from the data store, and in the latter case, the arguments - and expected behavior - are different and implementation dependent.



Instead, you should probably define a factory method like:

class MyModel(db.PolyModel):
  @classmethod
  def create(cls, foo, bar):
    # Do some stuff
    return cls(foo, bleh)

      

+1


a source







All Articles