__init__() not called automatically

Paul McNett p at ulmcnett.com
Thu May 26 00:55:52 EDT 2005


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




More information about the Python-list mailing list