[Tutor] /not/ instanciating
alan.gauld at btinternet.com
Sun Nov 16 23:41:08 CET 2008
"spir" <denis.spir at free.fr> wrote
> I have a type (say: T) which normally receives as main init argument
> an object that can be of any other type. Occasionally, this arg
> object may precisely be of type T. In this case, for several
> reasons, I wish not to "over-instanciate", rather that the
> constructor returns the source object unchanged. I did some research
> and trials on the topic, and found as sole solution to overload
> __new__ as shown below.
That's right because new is the constructor.
init is the initialiser. They are slightly different concepts which
Python makes explicit.
> Still, as said in the doc, __init__ was not skipped (what for?), I
> need to do it myself.
Because creating an object and initialising it are two different
> * Is there anything I should pay attention to?
You should always be careful of managing resources directly
in Python, its very rarely necessary. Kent has suggested an
alternative that avoids messing with new...
> * Why, then, is __init__ still executed when the instanciated object
> is 'manually' returned? What's the use of that feature?
Because you may want to control how an object is created
but also control how it is initialised. For example you may
create it in any of several different ways depending on
context (from a file or database, in memory, over a steam)
but then want to initialise it with the same data values
regardless of how it was created. If you don't want init
to do anything you can just use pass... Or if the superclasses
don't do anything just leave it out.
> * I find this an ugly distorsive practice. Isn't there a more
> graceful way not to instanciate?
Its very similar to how several other OOP languages work.
Lisp, Smalltalk, Objective C to name but 3 all have split
creatiion/initialisation. It is a powerful protocol for managing
object instantiation. In the vast majority of cases initialisation
is all that's needed.
> Or to simply return the desired object without caring of
The factory method approach suggested by Kent might
be better for your needs.
Author of the Learn to Program web site
More information about the Tutor