473,406 Members | 2,954 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

__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 12146
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Felix Wiemann | last post by:
Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called...
2
by: Steven Bethard | last post by:
Felix Wiemann wrote: > Steven Bethard wrote: >> http://www.python.org/2.2.3/descrintro.html#__new__ > > > I'm just seeing that the web page says: > > | If you return an existing object,...
7
by: Kent Johnson | last post by:
Are there any best practice guidelines for when to use super(Class, self).__init__() vs Base.__init__(self) to call a base class __init__()? The super() method only works correctly in multiple...
2
by: Thomas Bartkus | last post by:
If I insert an __init__ method in my own class definition, it is incumbent upon me to call the __init__ of any declared ancester to my new class object because my __init__ will override that of any...
6
by: Rob Cowie | last post by:
Hi all, Is there a simple way to call every method of an object from its __init__()? For example, given the following class, what would I replace the comment line in __init__() with to result...
8
by: kelin,zzf818 | last post by:
Hi, Today I read the following sentences, but I can not understand what does the __init__ method of a class do? __init__ is called immediately after an instance of the class is created. It...
3
by: Steven W. Orr | last post by:
When I go to create an object I want to be able to decide whether the object is valid or not in __init__, and if not, I want the constructor to return something other than an object, (like maybe...
3
by: 7stud | last post by:
When I run the following code and call super() in the Base class's __init__ () method, only one Parent's __init__() method is called. class Parent1(object): def __init__(self): print...
25
by: Erik Lind | last post by:
I'm new to Python, and OOP. I've read most of Mark Lutz's book and more online and can write simple modules, but I still don't get when __init__ needs to be used as opposed to creating a class...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.