initializing mutable class attributes

Shalabh Chaturvedi shalabh at cafepy.com
Mon Aug 30 16:06:29 EDT 2004


Dan Perl wrote:
> "Shalabh Chaturvedi" <shalabh at cafepy.com> wrote
>>In Python you either have an __init__ or you don't. There is no 'default
>>constructor' - or if there is, it does nothing. Since attributes can be
>>dynamically added to an instance (not just in __init__ but in any
>>method), it follows that the standard practice is to initialize instance
>>members in __init__ as it is always called before any other instance
>>method. Now that there is one way to do a thing, Python avoids the
>>introduction of another way (unless it is notably more productive). That
>>would lead to a whole set of questions about 'which way is better?
>>__init__ or the other way?'.
> 
> 
> It is a subjective issue indeed.  But I'll restrict my question to a simpler
> question.  By analogy to C++ and Java, why is __init__ not implemented to
> automatically invoke the __init__(self) of the parent classes?  I'm
> beginning to see a reason here, which is that C++ and Java allow you to
> overload the constructor and have a default constructor at the same time as
> another constructor with arguments.  C++ and Java then force you to create a
> default constructor for a parent class, even if it's empty, if you create a
> non-default constructor for it and you subclass the parent class.
> 
> In contrast, Python does not allow method overloading and I'm OK with that.
> It's a simplification that allows using Python in ways that are not possible
> with C++ and Java.  So Python cannot force you to have a 'default' __init__
> and allow you to have 'non-default '__init__'s at the same time.  I am
> answering my own question here, but that's OK and it would not have happened
> without this discussion.

Yes, if the parent class __init__ accepts parameters, how can Python 
call it automatically? Should it be automatic in some cases and 
non-automatic in others? (Answer: no, it's too ambiguous). Also what if 
there are multiple parent classes? As the Quixote folks put it, in the 
face of ambiguity, refuse the temptation to guess. (Btw, Python's 
solution for multiple parent classes completely knocks the socks off C++ 
[1])

Cheers,
Shalabh

[1] http://www.python.org/2.2.3/descrintro.html#cooperation




More information about the Python-list mailing list