initializing mutable class attributes
dperl at rogers.com
Mon Aug 30 21:32:47 CEST 2004
"Shalabh Chaturvedi" <shalabh at cafepy.com> wrote in message
news:mailman.2624.1093889688.5135.python-list at python.org...
> 'Why' is a very subjective question. People from different backgrounds
> may accept very different answers for why since it may always be in a
> specific context (why this instead of *that*?). The following is my idea
> of why:
> 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.
> Btw, now that there are descriptors, you can create descriptors that
> initialize instance members with default values when they are accessed.
> However, unless there is great advantage in your specific case, it might
> be just better to follow standard practice and make it easier for
> everyone else reading your code.
I'll have to look more into descriptors, I haven't used them yet and I see
there are many discussions on the topic in this newsgroup. I found your
"Python Attributes and Methods" page on cafepy.com and I'll take a look
More information about the Python-list