Custom constructors for models in Google App Engine (python)
Posted
by Nikhil Chelliah
on Stack Overflow
See other posts from Stack Overflow
or by Nikhil Chelliah
Published on 2010-05-30T07:05:30Z
Indexed on
2010/05/30
7:12 UTC
Read the original article
Hit count: 218
I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a contrived example, with no error-checking, etc.:
class Dog(db.Model):
name = db.StringProperty(required=True)
breeds = db.StringListProperty()
age = db.IntegerProperty(default=0)
def __init__(self, name, breed_list, **kwargs):
db.Model.__init__(**kwargs)
self.name = name
self.breeds = breed_list.split()
rufus = Dog('Rufus', 'spaniel terrier labrador')
rufus.put()
The **kwargs are passed on to the Model constructor in case the model is constructed with a specified parent
or key_name
, or in case other properties (like age
) are specified. This constructor differs from the default in that it requires that a name
and breed_list
be specified (although it can't ensure that they're strings), and it parses breed_list
in a way that the default constructor could not.
Is this a legitimate form of instantiation, or should I just use functions or static/class methods? And if it works, why aren't custom constructors used more often?
© Stack Overflow or respective owner