__init__() not called automatically

John Roth newsgroups at jhrothjr.com
Thu May 26 08:43:09 EDT 2005


"Sriek" <scharan20 at gmail.com> wrote in message 
news:1117081917.760603.82610 at z14g2000cwz.googlegroups.com...
> hi,
> i come from a c++ background. i ws happy to find myself on quite
> familiar grounds with Python. But, what surprised me was the fact that
> the __init__(), which is said to be the equivlent of the constructor in
> c++, is not automatically called. I'm sure there must be ample reason
> for this. I would like to know why this is so? This is my view is more
> burden on the programmer.

It depends on what you mean by a burden. If the init methods of
each subclass was always called, then you'd have to work out how
to make them cooperate in all cases. The way C++ works, it has to
call the constructors because the vtable has explicit sections for each
of the base classes, recursively to the (possibly multiple) bases of
the tree. In Python, that isn't true - you get one instance regardless
of the number of base classes or structure of the tree, and that
single instance contains all the identifiers needed. It's up to the
class you instantiate to decide how to build the instance.

> Similarly, why do we have to explicitly use the 'self' keyword
> everytime?

Python has no way of knowing, at compile time, whether an
identifier is an instance/class variable or a module/builtin.
Putting the instance among the parameters lets you treat it as
a local variable which the compiler is quite capable of handling.

Remember that you're dealing with a highly dynamic environment;
inspection of the single source module will not tell you enough to
make this distinction.

John Roth
>
> Every kind of help would be welcome.
> 




More information about the Python-list mailing list