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. 21 12290
On 25 May 2005 21:31:57 -0700, Sriek <sc*******@gmai l.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
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
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.
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
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.
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
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.
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
"Sriek" <sc*******@gmai l.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
nonetheless, so that the instance is initialized a second time. For
example, please consider the following class (a singleton in this case):
>>> class C(object):
.... instance = None
.... def __new__(cls):
.... if C.instance is None:
|
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, the constructor call will still
> | call its __init__ method. If you return an object of a different
|
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 inheritance when the
base classes are written to expect it, so "Always use super()" seems
like bad advice. OTOH sometimes you need super() to get correct
behaviour. ISTM "Only use super() when you know you need it" might be
|
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 ancester I declare in the
header. If I fail to call the ancesters __init__, then it won't happen.
The ancester object won't be initialized.
But
If I *don't* insert my own __init__ in my new class, then any declared
ancester __init__ will...
|
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 in both methods being called?
I understand that I could just call each method by name but I'm looking
for a mechanism to avoid this.
| |
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 would be tempting but incorrect to call this the
constructor of the class. It's tempting, because it looks like a
constructor (by convention, __init__ is the first method defined for
the class), acts like one (it's the first piece of code executed in...
|
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 None). I seem to be
having problems. At the end of __init__ I say (something like)
if self.something < minvalue:
del self
return None
and it doesn't work. I first tried just the return None, then I got crafty
|
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 "Parent1 init called."
self.x = 10
class Parent2(object):
|
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 instance by assignment. For
some strange reason the literature seems to take this for granted. I'd
appreciate any pointers or links that can help clarify this.
Thanks
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |