469,568 Members | 1,446 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,568 developers. It's quick & easy.

__init__() not called automatically

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.

Jul 19 '05 #1
21 9757
On 25 May 2005 21:31:57 -0700, Sriek <sc*******@gmail.com> wrote:
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.
class C: .... def __init__(self): print "Hello"
.... c = C()

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/genera...ions-and-calls

Every kind of help would be welcome.
No worries,

Tim

--
http://mail.python.org/mailman/listinfo/python-list

Jul 19 '05 #2
Sriek wrote:
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.
class A(object): .... def __init__(self):
.... print "in __init__"
.... a = A()

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!
--
pkm ~ http://paulmcnett.com

Jul 19 '05 #3
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.

Jul 19 '05 #4
Paul McNett wrote:
Sriek wrote:
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
Jul 19 '05 #5
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. ;)

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

Jul 19 '05 #6
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

Jul 19 '05 #7
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.

Jul 19 '05 #8
On Wed, 25 May 2005 21:31:57 -0700, Sriek wrote:
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

Jul 19 '05 #9

"Sriek" <sc*******@gmail.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.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.


Jul 19 '05 #10
On 25 May 2005 21:31:57 -0700,
"Sriek" <sc*******@gmail.com> wrote:
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

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 19 '05 #11
"Sakesun Roykiattisak" <sa*****@boonthavorn.com> wrote in message
news:ma**************************************@pyth on.org...
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.
Jul 19 '05 #12
Sriek wrote:
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
Jul 19 '05 #13
I guess you are right.

Jul 19 '05 #14
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.

Jul 19 '05 #15
Paul McNett wrote:
Sriek wrote:

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

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 !-)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '05 #16
bruno modulix <on***@xiludom.gro> wrote:
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.
Jul 19 '05 #17
bruno modulix wrote:
Paul McNett wrote:

Sriek wrote:

(snip)

Similarly, why do we have to explicitly use the 'self' keyword
everytime?
This is closer to a wart, IMO,


Here's one of the shorter threads discussing 'self'. I remember one
looooong running thread, but can't seem to find it, at the minute

http://groups.google.co.uk/group/com...c80d8b1c92101c

J
Jul 19 '05 #18
Roy Smith a écrit :
bruno modulix <on***@xiludom.gro> wrote:
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".


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...
Jul 19 '05 #19
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.

Andrew Koenig wrote:
"Sakesun Roykiattisak" <sa*****@boonthavorn.com> wrote in message
news:ma**************************************@pyt hon.org...
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.


Jul 19 '05 #20
If you really want, you can customize the object system
to automatically call __init__, via a custom metaclass.
There is an example in my ACCU lectures (cooperative_init.py):

http://www.reportlab.org/~andy/accu2...rsofpython.zip

Michele Simionato

Jul 19 '05 #21
On 26 May 2005 11:54:33 -0400, Roy Smith <ro*@panix.com> wrote:
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.


To be fair, it's easy to use 'this' by accident if you've recently
been working with Java. I've done it myself. It takes me an hour or to
reset my brain, and for a short while, there are bloody 'this'es,
braces and semi-colons everywhere.

Sanity soon returns, though.

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 19 '05 #22

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Felix Wiemann | last post: by
7 posts views Thread by Kent Johnson | last post: by
2 posts views Thread by Thomas Bartkus | last post: by
6 posts views Thread by Rob Cowie | last post: by
8 posts views Thread by kelin,zzf818 | last post: by
3 posts views Thread by Steven W. Orr | last post: by
25 posts views Thread by Erik Lind | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.