no return values for __init__ ??

Gordon McMillan gmcm at hypernet.com
Thu Jan 6 16:58:11 EST 2000


Helge Hess wrote:

> Gordon McMillan wrote:
> > Helge Hess writes:
> > 
> > What happens when a derived class chains to the base class
> > __init__ and the base class __init__ changes "self"?
> 
> Good question. Depends on what one tries to accomplish with
> different return values, usually it would look like:
> 
>   def __init__(self...
>      s = super.__init__(self...
>      if (s is not None) & (s is not self): return s
>      self.a = 5
>      return self

OK, but it introduces a "gotcha". As in, what happened to the 
stuff I set up before calling super.__init__, (which is not only 
valid, but often useful).

> BTW: I also always wondered why Python has None as the default
> return value. 'self' seems better to me as one could make
> compound method calls without additional work while None has no
> benefit I can see (maybe better RC behaviour ?).

It's consistent with function behavior (which has no self to 
return), and after all, a method (when viewed on the class 
object) is a function.
 
> > How about MI?
> 
> This is related to the above.

With yet more "gotchas".  The (one and only) base class 
constructor that could change "self" would have to be the first 
one executed.

> There is no conceptual difference between __init__ returning a
> value and any other method returning a value.  

Not if you don't accept the axiom that __init__ is "just another 
method". In fact, as an initializer, __init__ is a lot less special 
that constructors are in most languages.
 
> > If really you want to customize the class, you can assign to
> > the instance's __class__ attribute.
> 
> Ok, this is getting much nearer to my goal although it is much
> less convenient. Eg this would probably break abstraction since
> the state of the object needs to be converted. Returning a new
> object seems much easier and more consistent to me.

I believe it does more of what you want than what you asked 
for, since it doesn't discard the instance, it simply replaces a 
branch of the attribute lookup tree.

Abstraction is one of those notions that Python tosses out the 
window, yet expresses very well.
 
> > Having "self" be a complete object when __init__ runs  means
> > the language doesn't have to come up with a bunch of arcane
> > rules about default constructors, order in which base class
> > constructors are called etc.
> 
> I don't understand what you are trying to say. We are talking
> about return values. In every invocation of __init__ the object
> is as complete as it can be.

It just may get unexpectedly tossed ;-).
 


- Gordon




More information about the Python-list mailing list