Custom constructors for models in Google App Engine (python)

I am returning to programming for the Google App Engine, and I found instances in the old unused code in which I wrote constructors for models. This seems like a good idea, but there is no mention of this on the Internet, and I canโ€™t check if it works. Here's a far-fetched example, without 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() 

** kwargs are passed to the Model constructor if the model is built with the specified parent or key_name or if other properties are specified (for example, age ). This constructor differs from the default in that it requires the name and breed_list (although it cannot guarantee that they are strings), and it analyzes the breed_list in such a way that the default constructor could not.

Is this a legal form of instantiation, or am I just using static / class functions or methods? And if that works, why aren't custom constructors used more often?

+4
source share
2 answers

In your example, why not use the default syntax instead of the custom constructor:

 rufus = Dog( name='Rufus', breeds=['spaniel','terrier','labrador'] ) 

Your version makes it less semantically understood IMHO.

Regarding overriding model constructors, Google recommends against it (see for example: http://groups.google.com/group/google-appengine/browse_thread/thread/9a651f6f58875bfe/111b975da1b4b4db?lnk=gst&q=python+constructors#111b975da1b4bd and therefore we do not see this in Google code. I think this is unfortunate, because overriding the constructor can be useful in some cases, for example, creating a temporary property.

One problem that I know about is the extension with Expando, everything that you define in the constructor is automatically serialized in the protocol buffer. But for the base models, I'm not sure what the risks are, and I would also be happy to know more.

+2
source

Usually there is no need to do something like this; the default constructor will assign name , and when working with a list it almost always makes sense to pass the actual list instead of a string separated by spaces (just imagine the pleasure if you passed the "cocker spaniel" instead of just the "spaniel" "there, firstly .. .).

However, if you really need to do the calculations when instantiating the Model subclass, there is probably nothing wrong with it. I think most people probably prefer to get the data in the right form and then create the entity, so you don't see such examples.

+1
source

Source: https://habr.com/ru/post/1311334/


All Articles