initializing mutable class attributes
shalabh at cafepy.com
Mon Aug 30 20:16:16 CEST 2004
Dan Perl wrote:
> After seeing a few replies (yours, Benjamin Niemann's and Peter Otten's) to
> my initial posting, I think I am getting the picture that there is a
> conscious decision to keep the use of __init__ the way it is and just make
> people learn it and learn it early enough.
> That's a valid approach and I'll
> accept it.
That's nice :)
> No one, including you, has given me a reason WHY __init__ is implemented
> this way. I am not bashing you for that, I would just still like to hear
> that 'WHY'. I'm sure that this implementation has some advantages. But,
> coming from a C++ and Java background, where parent default constructors are
> automatically invoked (well, not always, and that is something that users
> have to learn too), I find that that approach has some clear advantages.
'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
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?'.
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.
> PS: Does my last name attract the wrong kind of attention from people in
> this newsgroup?
I don't think so.
More information about the Python-list