__init__() not called automatically

S

Sriek

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.
Similarly, why do we have to explicitly use the 'self' keyword
everytime?

Every kind of help would be welcome.
 
T

Tim Leslie

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.
.... def __init__(self): print "Hello"
....Hello

This looks like __init__ being called automatically to me. Are you
doing something different?
Similarly, why do we have to explicitly use the 'self' keyword
everytime?
http://www.python.org/doc/faq/gener...ed-explicitly-in-method-definitions-and-calls


Every kind of help would be welcome.

No worries,

Tim
 
P

Paul McNett

Sriek said:
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.

What do you mean by automatically? :

Python 2.4.1 (#2, May 5 2005, 09:45:41)
[GCC 4.0.0 20050413 (prerelease) (Debian 4.0-0pre11)] on linux2
Type "help", "copyright", "credits" or "license" for more information..... def __init__(self):
.... print "in __init__"
....in __init__

So __init__ is definitely called upon instantiation. It is true that if
you derive from A and override __init__, A.__init__ won't be called
unless done so explicitly like:

class B(A):
def __init__(self):
print "in B.__init__()"
super(B, self).__init__()
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 isn't that much practical burden, and IMO it makes perfect sense.
When you override a method of a class, you want to have to explicitly
call superclass code, not have it run automatically, else you lose
control of the flow.

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

This is closer to a wart, IMO, but once you've used Python for a while
you'll come to understand why this is so. Basically, everything in
Python is either a namespace or a name in a namespace. In the case of
the self reference which Python sends as the first arg automatically,
the method needs to bind that to a local name which is, by convention
only, 'self'.

Every kind of help would be welcome.

You've found the right place to hang out. Welcome!
 
S

Sriek

Tim pointed out rightly that i missed out the most crucial part of my
question.
i should have said that __init__() is not called automatically only for
the inheritance hierarchy. we must explicitly call all the base class
__init__() fuctions explicitly.
i wanted a reason for that.
Thanks Tim.
 
S

Steven Bethard

Paul said:
Sriek said:
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.
[snip]

It is true that if
you derive from A and override __init__, A.__init__ won't be called
unless done so explicitly like:

class B(A):
def __init__(self):
print "in B.__init__()"
super(B, self).__init__()
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 isn't that much practical burden, and IMO it makes perfect sense.
When you override a method of a class, you want to have to explicitly
call superclass code, not have it run automatically, else you lose
control of the flow.

I'd like to reiterate this point. Say I have a class like:

class A(object):
def __init__(self, x):
self.x = x
print 'A.__init__'

and an inheriting class like:

class B(A):
def __init__(self, y):
...
print 'B.__init__'
...

If 'y' is the same thing as 'x', then I probably want to write B like:

class B(A):
def __init__(self, y):
super(B, self).__init__(y)
print 'B.__init__'

But what if 'x' has to be computed from 'y'? Then I don't want the
super call first. I probably want it last (or at least later), e.g.:

class B(A):
def __init__(self, y):
print 'B.__init__'
x = self._compute_x(y)
super(B, self).__init__(x)

If the superclass constructor is automatically called, how will it know
which meaning I want for 'y'? Is 'y' equivalent to 'x', or is it
something different? Since Python can't possibly know this for sure, it
refuses the temptation to guess, instead requiring the user to be explicit.

STeVe
 
S

Sakesun Roykiattisak

Does c++ call base class constructor automatically ??
If I'm not wrong, in c++ you also have to call base class constructor
explicitly.
Python just do not enforce the rule. You can leave it as desire.

BTW, I've once been an C++ expert. Knowing python kill that skill.
However, I'm not regret. I have c++ compiler installed, but I don't even
bother validate my last paragraph assertion. Too disgusting. ;)
 
S

Sriek

if i understand C++ right, in c++ you CAN explicitly call the base
constructor ( for eg. if it requires some particular arguements ), but,
the compiler automatically has to call the base class constructor ( see
the rules for constructing an object of the derived classes ).

But, yes, C++ can be too disgusting sometimes. But, i like the C++
design philosophy ( read D & E of C++ ? ), the rasons for various
features are intellgently put inplace.

Correct me if i am wrong about both the paragraphs. ok? T
Thanks
 
S

Sriek

maybe like this:
we can have the default behaviour as calling the default constructor
( with default arguements where required ). Along with this, keep the
option open to call constructors explicitly.

My only contention is that there may be a greater reason for this rule
in the Python Language. thats it.
 
J

Jeremy Sanders

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

I didn't like that when starting Python. Now when I look back at C++ code,
I find it very hard to work out which variables and methods and members,
and which are not, unless the author used a clear naming convention.

Jeremy
 
J

John Roth

Sriek said:
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
 
D

Dan Sommers

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

Why do they (the C++ programmers) prepend "m_" to otherwise perfectly
good member names?

Regards,
Dan
 
A

Andrew Koenig

Does c++ call base class constructor automatically ??
If I'm not wrong, in c++ you also have to call base class constructor
explicitly.

In C++, if you don't call a base-class constructor (I am saying "a" rather
than "the" because there might be more than one direct base class), it is
called automatically with no arguments. The only case in which you must
call it explicitly is if it will not accept an empty argument list.
 
S

Steven Bethard

Sriek said:
maybe like this:
we can have the default behaviour as calling the default constructor
( with default arguements where required ). Along with this, keep the
option open to call constructors explicitly.

Ok, so here's another example:

def init(self):
print "An __init__ method, but in what class?!!"
print "Oh, this class: %s" % type(self).__name__

class C(object):
pass

C.__init__ = init

So how would the compiler know that init() is a constructor for the C
object? (You can figure that out at runtime, but I don't see how you can
generally figure that out at compile time.)

STeVe
 
S

Sri Charan

The compiler also calls the default arguement constructor
automatically, if such a constructor is provided for the base
class(es); but, this becomes a special case of what has been said by
Andrew Koenig.

So, it is NOT just the no arguement constructor that is automatically
called; note that the default arguement constructor is kinda put in
place because sometimes, the user may call the constructor with no
arguements, while the object actually needs some values for proper
construction.
 
B

bruno modulix

Paul said:
Sriek wrote:
(snip)


This is closer to a wart, IMO,

I've always explicitelly used the (implied) 'this' pseudo-pointer in
Java, C++ etc. The wart is in all those languages that don't makes it
mandatory IMHO !-)
 
R

Roy Smith

bruno modulix said:
I've always explicitelly used the (implied) 'this' pseudo-pointer in
Java, C++ etc. The wart is in all those languages that don't makes it
mandatory IMHO !-)

And the correlary wart in Python is that the first argument to a
method is not required to be called "self". The vast majority of
people use "self", but every once in a great while you run into some
yahoo who feels this is the right place to express his creativity and
call it "this", or "obj", or some other obfuscation.
 
B

Bruno Desthuilliers

Roy Smith a écrit :
And the correlary wart in Python is that the first argument to a
method is not required to be called "self".

Well, I would not call this a wart. Because when it's a class method,
naming the fisrt param 'cls' could seem more appropriate !-)
The vast majority of
people use "self", but every once in a great while you run into some
yahoo who feels this is the right place to express his creativity and
call it "this", or "obj", or some other obfuscation.

Then every python programmer in its own mind will throw away this code
with mimics of disgust, and everything is fine.

More seriously, I prefer to have some bozo using this instead of self -
which I can easily correct if needed - than having to deal with implicit
this in a whole code base...
 
S

Sakesun Roykiattisak

Wow.. Andrew Koenig.. I found your name in many c++ books I read. Never
know you are hanging around in python python mailing-list.
(or perhaps python newsgroup, whatever it is)

Thanks for the explanation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top