OOP / language design question
Duncan Booth
duncan.booth at invalid.invalid
Tue Apr 25 07:29:22 EDT 2006
cctv.star at gmail.com wrote:
> Heiko Wundram wrote:
>> Because sometimes you don't want to call the base classes constructors?
> Sounds strange to me at the moment, but I'll try to adjust to this
> thought.
It makes sense in more static languages such as C++. The base class is
initialised by the constructor, so you have to do everything possible to
ensure that initialisation is done before you actually try to use any part
of the base class. Weird things can still happen in C++ if you start
calling methods too soon (e.g. to calculate some of the base constructor's
parameters): you can find uninitialised member variables and you might not
get exactly the virtual methods you expected.
Python is more laid back about these things. The object itself already
exists when __init__ is first called. It already has a type, which
(unlike C++) isn't going to change part way through. All that is missing
are a few attributes, and if you try to access them too soon you'll get an
exception rather than a random value.
It makes sense therefore to give the programmer the scope to override the
expected sequence of initialisation for those rare cases where it actually
matters. The programmer also gets enough scope to shoot themselves in the
foot, but Python programmers are expected to be intelligent enough not to
do that accidentally.
Usually though, if a subclass doesn't immediately call the base class
constructors as the first thing it does in __init__ it indicates poor code
and should be refactored.
BTW, the same arguments apply to destructors: if you have a __del__ method
and need to call the base __del__ methods you have to do that manually as
well.
More information about the Python-list
mailing list