473,836 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

consequences of not calling object.__init__ ?

So when I'm writing a class and I define an __init__ method, I sometimes
haven't called object.__init__ , e.g.:

class C(object):
def __init__(self, x):
self.x = x

instead of

class C(object):
def __init__(self, x):
super(C, self).__init__( )
self.x = x

Looking at:

http://www.python.org/2.2.3/descrintro.html#__new__
"The built-in type 'object' has a dummy __new__ and a dummy __init__"

seems to suggest that the super call here is unnecessary. It's also not
made in the Super class example from that document:

http://www.python.org/2.2.3/descrint...l#superexample

I'm trying to get in the habit of calling super in all __init__ methods,
but it seems like it's unnecessary when the only superclass is object.
Assuming that the base class of C doesn't get changed from object, are
there consequences of not making this call?
Steve
Jul 18 '05 #1
6 3719
in the code that follows, instances of E haven't been through D's
rigorous initiation process

.. class C(object):
.. def __init__(self):
.. print "C"
..
.. class D(object):
.. def __init__(self):
.. print "D"
.. super(D, self).__init__( )
..
.. class E(C, D):
.. def __init__(self):
.. print "E"
.. super(E, self).__init__( )

Jul 18 '05 #2
Steven Bethard wrote:
So when I'm writing a class and I define an __init__ method, I sometimes
haven't called object.__init__ , e.g.:

class C(object):
def __init__(self, x):
self.x = x

instead of

class C(object):
def __init__(self, x):
super(C, self).__init__( )
self.x = x

Looking at:

http://www.python.org/2.2.3/descrintro.html#__new__
"The built-in type 'object' has a dummy __new__ and a dummy __init__"

seems to suggest that the super call here is unnecessary. It's also not
made in the Super class example from that document:

http://www.python.org/2.2.3/descrint...l#superexample

I'm trying to get in the habit of calling super in all __init__ methods,
but it seems like it's unnecessary when the only superclass is object.
Assuming that the base class of C doesn't get changed from object, are
there consequences of not making this call?

The principal one that I can see is that you are relying on this
implementation feature to maintain forward compatibility, since I'm not
aware of any pronouncement that says "object will *always* have a dummy
__init__".

There's also the possibility that you might want to use a different base
class later (for example, setting

object = mySuperDebugObj ect

for debugging purposes). If that object has an __init__() method you'll
have to put the calls in then anyway.

Perhaps a relevant question is how long it takes to call the __init__
method using super.

sholden@dellboy ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s "
class C(object):
def __init__(self, x):
self.x = x" "C(1)"
100000 loops, best of 3: 2.69 usec per loop

sholden@dellboy ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s "
class C(object):
def __init__(self, x):
super(C, self).__init__( )
self.x = x" "C(1)"
100000 loops, best of 3: 5.58 usec per loop

So, even on my cronky old 1.3 GHz laptop [1] you only lose 3
microseconds per object creation. You'll have to decide how significant
that is.

regards
Steve

[1]: Freaky - I had just typed this when the doorbell went, and it was
the UPS driver delivering the new laptop!
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #3
John Lenton wrote:
in the code that follows, instances of E haven't been through D's
rigorous initiation process

. class C(object):
. def __init__(self):
. print "C"
.
. class D(object):
. def __init__(self):
. print "D"
. super(D, self).__init__( )
.
. class E(C, D):
. def __init__(self):
. print "E"
. super(E, self).__init__( )


Ahh, there's the example I was looking for. =)

Thanks!

Steve
Jul 18 '05 #4
Steven Bethard wrote:
So when I'm writing a class and I define an __init__ method, I sometimes
haven't called object.__init__ , e.g.:

class C(object):
def __init__(self, x):
self.x = x

instead of

class C(object):
def __init__(self, x):
super(C, self).__init__( )
self.x = x

Looking at:

http://www.python.org/2.2.3/descrintro.html#__new__
"The built-in type 'object' has a dummy __new__ and a dummy __init__"

seems to suggest that the super call here is unnecessary. It's also not
made in the Super class example from that document:

http://www.python.org/2.2.3/descrint...l#superexample

I'm trying to get in the habit of calling super in all __init__ methods,
but it seems like it's unnecessary when the only superclass is object.
Assuming that the base class of C doesn't get changed from object, are
there consequences of not making this call?


Yes!

Consider what happens if you multi-subclass from the above C class and
another class D.

class E(C, D):
def __init__(self, x):
super(E, self).__init__( x)
# some initialization for E

Now E.__mro__ is (E,C,D,object). So:

1. E's __init__ should call C's __init__ (this happens due to super call
in E.__init__)

2. C's __init__ should call D's __init__ (*this is why you need the
super call in C.__init__*)

Without it, D.__init__ will not be called. Note that D.__init__ should
not take any parameters in this case. Parameter similarity may be an
issue in call-next-method technique.

However, if you know you will not mutli-subclass from C, you may leave
out the super call.

HTH,
Shalabh
Jul 18 '05 #5
Steve Holden wrote:
The principal one that I can see is that you are relying on this
implementation feature to maintain forward compatibility, since I'm not
aware of any pronouncement that says "object will *always* have a dummy
__init__".


Maybe there's no such pronouncement, but unless there is a
clear statement somewhere (and I believe I've missed it, if
there is) that reads "one should *always* call __init__ on the
superclass even if one is just subclassing object and not
dealing with multiple inheritance situations", then I would
submit that the majority of Python code written using new-style
classes would be broken should what you suggest above ever
actually happen... starting with much of the code in the
standard library (based on a quick glance at those modules
whose contents match the re pattern "class .*(object):" .

-Peter
Jul 18 '05 #6
Peter Hansen, Quarta 29 Dezembro 2004 01:04, wrote:
Maybe there's no such pronouncement, but unless there is a
clear statement somewhere (and I believe I've missed it, if
there is) that reads "one should *always* call __init__ on the
superclass even if one is just subclassing object and not
dealing with multiple inheritance situations", then I would
submit that the majority of Python code written using new-style
classes would be broken should what you suggest above ever
actually happen... starting with much of the code in the
standard library (based on a quick glance at those modules
whose contents match the re pattern "class .*(object):" .


Things are kind weird at this point, since there are too many things to
think about and to make a decision on what should be done and what is
recommended to be done...

Quoting from http://www.python.org/peps/pep-0008.html:

"""
(...)
Designing for inheritance
(...)
Also decide whether your attributes should be private or not.
The difference between private and non-public is that the former
will never be useful for a derived class, while the latter might
be. Yes, you should design your classes with inheritence in
mind!
(...)
"""

So, I don't really know which is correct: to always call the constructor of
the parent class or just do that when it is needed by design...

I think that based on the above quotation from PEP-0008 code in the standard
library should be calling the parent class constructor. But then, I'm one
of the people who never do that :-)

--
Godoy. <go***@ieee.org >

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
9635
by: Murat Tasan | last post by:
i have a quick question... is there a way to obtain the reference to the object which called the currently executing method? here is the scenario, i have a class and a field which i would like to populate with a reference to the object that constructed this current object. i would attempt to accomplish this by setting the appropriate field from within the constructor... i figured it might be obtainable from the stack trace, but that...
1
2828
by: MAF | last post by:
Is there anyway that I can find out what object called another object? ObjectABase ObjectA inherits from ObjectABase objectA calls objectB I want to invoke a method in ObjectABase?
4
1218
by: Alan LeHun | last post by:
Is it possible for a subroutine to get a reference to the object instance that has called it? IOW, class1 creates an instance of class2 and calls one if its subroutines and I would like that subroutine to have a reference to the original class1 object that called it. -- Alan LeHun
6
7225
by: Mirek Endys | last post by:
Hello all, another problem im solving right now. I badly need to get typeof object that called static method in base classe. I did it by parameter in method Load, but i thing there should be way, how to get this information in called method. Thanks. public abstract class BaseClass {
7
3343
by: vsr | last post by:
I am calling one Method in Common class from different classes and i want to know from which object the call is coming from.. is there any way?
0
861
by: stormist | last post by:
I utilize a COM library to receive historical quote data on currencies. My problem is the constructors of the event are fixed. m_HistoryLookupClass.MinuteReceived += new _IHistoryLookup2Events_MinuteReceivedEventHandler(m_HistoryLookupClass_MinuteReceived); void m_HistoryLookupClass_MinuteReceived(string bsData) { ... //send data here }
0
949
by: Evan Klitzke | last post by:
Hi list, I was reading this article: http://fuhm.net/super-harmful/ and didn't understand the comment about calling super(Foo, self).__init__() when Foo inherits only from object. Can someone on the list elaborate more on why one should do this? -- Evan Klitzke <evan@yelp.com>
1
2361
by: vlmcntrl | last post by:
I'm building a website leaning heavily on js and ajax. I am trying to make the js object oriented which is fine until I get to ajax. I'm looking for a way to call my ajax onreadystatechange in the same object as the one who called it. I think that references would work, if there were such a thing in js. Does anyone have any idea how to do this.
1
1799
by: Maese Fernando | last post by:
Hi, I'm getting an odd error while trying to call the __init__ method of a super class: BaseField.__init__(self) TypeError: unbound method __init__() must be called with BaseField instance as first argument (got nothing instead)
0
9812
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, 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...
0
10824
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, 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...
0
10533
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 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...
1
10579
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,...
0
10244
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9362
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6975
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();...
0
5813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3103
bsmnconsultancy
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...

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.