__init__ explanation please

4 views
Skip to first unread message

Erik Lind

unread,
Jan 12, 2008, 7:35:57 PM1/12/08
to
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


Daniel Fetchinson

unread,
Jan 12, 2008, 7:56:09 PM1/12/08
to pytho...@python.org

I'm not sure if I understand your question correctly but maybe this will help:

If you want code to be run upon creating an instance of your class you
would use __init__. Most common examples include setting attributes on
the instance and doing some checks, e.g.

class Person:
def __init__( self, first, last ):
if len( first ) > 50 or len( last ) > 50:
raise Exception( 'The names are too long.' )
self.first = first
self.last = last

And you would use your class like so,

p1 = Person( 'John', 'Smith' )
p2 = Person( "Some long fake name that you don't really want to
except, I don't know if it's really longer than 50 but let's assume it
is", "Smith" )
# This last one would raise an exception so you know that something is not okay

HTH,
Daniel

Colin J. Williams

unread,
Jan 12, 2008, 7:58:18 PM1/12/08
to pytho...@python.org
You don't always need __init__ if
__new__ is used with a "new" class.

Colin W.

Daniel Fetchinson

unread,
Jan 13, 2008, 3:08:45 AM1/13/08
to pytho...@python.org
Please keep discussion on the list......

> > I'm not sure if I understand your question correctly but maybe this will
> > help:
> >
> > If you want code to be run upon creating an instance of your class you
> > would use __init__. Most common examples include setting attributes on
> > the instance and doing some checks, e.g.
> >
> > class Person:
> > def __init__( self, first, last ):
> > if len( first ) > 50 or len( last ) > 50:
> > raise Exception( 'The names are too long.' )
> > self.first = first
> > self.last = last
> >
> > And you would use your class like so,
> >
> > p1 = Person( 'John', 'Smith' )
> > p2 = Person( "Some long fake name that you don't really want to
> > except, I don't know if it's really longer than 50 but let's assume it
> > is", "Smith" )
> > # This last one would raise an exception so you know that something is not
> > okay
> >
> > HTH,
> > Daniel
>

> Is not the code run when I create an instance by assignement somewhere else?
>
> I take the point that one might want to check for potential exceptions
> immediately, but most examples in the literature aren't doing that and don't
> seem to be doing anything that would not be done when creating an instance
> by assignment later somewhere. I'm missing something basic here.

What do you mean by "create an instance by asignment somewhere else"?

Jeroen Ruigrok van der Werven

unread,
Jan 13, 2008, 5:46:41 AM1/13/08
to Erik Lind, pytho...@python.org
-On [20080113 01:41], Erik Lind (el...@spamcop.net) wrote:
>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.

I personally tend to see __init__ or __new__ as equivalent to what other
languages call a constructor.

(And I am sure some people might disagree with that. ;))

--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
The riddle master himself lost the key to his own riddles one day, and
found it again at the bottom of his heart.

Fredrik Lundh

unread,
Jan 13, 2008, 7:31:05 AM1/13/08
to pytho...@python.org
Jeroen Ruigrok van der Werven wrote:

> I personally tend to see __init__ or __new__ as equivalent to what other
> languages call a constructor.
>
> (And I am sure some people might disagree with that. ;))

given that they do different things, I'm not sure it's that helpful to
describe them *both* as constructors.

</F>

Fredrik Lundh

unread,
Jan 13, 2008, 7:44:58 AM1/13/08
to pytho...@python.org
Erik Lind wrote:

> 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.

nothing is ever created by plain assignment in Python; to create a class
instance in Python, you *call* the class object. an example:

class MyClass:
pass

# create three separate instances
obj1 = MyClass()
obj2 = MyClass()
obj3 = MyClass()

(it's the () that creates the object, not the =)

if you want to initialize the method's state (that is, set some
attributes), you can do that from the outside:

obj1.attrib = "some value"

or in an "initialization" method in the class:

class MyClass:
def init(self):
self.attrib = "some value"

obj1 = MyClass()
obj1.init()

but in both cases, you'll end up with an inconsistent object state (in
this case, no attribute named "attrib") if you forget to do this.

obj1 = MyClass()
print obj1.attrib # this will fail

to avoid such mistakes, you can use __init__ instead. this is just a
initialization method that's automatically called by Python *after* the
object is created, but *before* the call to the class object returns.

class MyClass:
def __init__(self):
self.attrib = "some value"

obj1 = MyClass()
print obj1.attrib # this will succeed

also, any arguments that you pass to the class object call are passed on
to the initialization method.

class MyClass:
def __init__(self, value):
self.attrib = value

obj1 = MyClass("hello")
print obj1.attrib # prints "hello"

as Jeroen points out, this is pretty much the same thing as a
constructor in other languages -- that is, a piece of code that's
responsible for setting up an object's state.

Python's a bit different; the object is in fact created before the
call to __init__, but this doesn't matter much in practice; if
construction fails, the assignment will fail, so the object will be
lost, and is reclaimed by the GC later on.

(unless you explicitly store a reference to the object somewhere else,
of course:

>>> class MyClass:
... def __init__(self):
... global secret
... secret = self
... raise ValueError("oops! failed!")
... def method(self):
... print "here I am!"
...

>>> obj = MyClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __init__
ValueError: oops! failed!

>>> obj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'obj' is not defined

>>> secret.method()
here I am!

)

finally, if you want full control also over the actual creation of the
object, more recent Python versions support a __new__ method that can be
used instead of __init__, or as a complement. but that's an advanced
topic, and is nothing you need to worry about while trying to the hang
of class basics.

hope this helps!

</F>

Ben Finney

unread,
Jan 13, 2008, 7:58:29 AM1/13/08
to
Jeroen Ruigrok van der Werven <asm...@in-nomine.org> writes:

> -On [20080113 01:41], Erik Lind (el...@spamcop.net) wrote:
> >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.
>
> I personally tend to see __init__ or __new__ as equivalent to what
> other languages call a constructor.

That's getting the two of them confused. __new__ is a constructor,
__init__ is not.

> (And I am sure some people might disagree with that. ;))

It isn't really a matter for much debate.

<URL:http://www.python.org/doc/ref/customization.html>

__new__ is the constructor: it creates the instance and returns it.

Along the way, it calls __init__ on the *already-created* instance, to
ask it to initialise itself ready for use. So, __init__ is an
"initialiser" for the instance.

Python, unlike many other OO languages, fortunately has these two
areas of functionality separate. It's far more common to need to
customise instance initialisation than to customise creation of the
instance. I override __init__ for just about every class I write; I
can count the number of times I've needed to override __new__ on the
fingers of one foot.

--
\ "Reichel's Law: A body on vacation tends to remain on vacation |
`\ unless acted upon by an outside force." -- Carol Reichel |
_o__) |
Ben Finney

A.T.Hofkamp

unread,
Jan 14, 2008, 3:01:42 AM1/14/08
to

I think you mean the following:
You'd like to do

p = Person('me', 'here', 31)

and you are wondering why you need the __init__() function in

class Person(object):
def __init__(self, name, addres, age):
self.name = name
self.address = address
self.age = age

right?

If so, the answer is that while you think you are doing "Person('me', 'here', 31)",
you are in reality executing "Person.__init__(self, 'me', 'here', 31)", where
'self' is refers to a shiny new, empty object created for you.

(and the 'self' is obtained by the Person.__new__ function I think, but others
here have much better knowledge about this).


Sincerely,
Albert

Ben Finney

unread,
Jan 14, 2008, 6:18:44 AM1/14/08
to
"A.T.Hofkamp" <h...@se-162.se.wtb.tue.nl> writes:

> while you think you are doing "Person('me', 'here', 31)", you are in
> reality executing "Person.__init__(self, 'me', 'here', 31)", where
> 'self' is refers to a shiny new, empty object created for you.

This is misleading, and founders on many discrepancies, not least of
which is that '__init__' always returns None, yet the 'Person()' call
returns the new instance. So it's quite untrue to say that one is "in
reality" calling the '__init__' method.

What one is "in reality" calling is the '__new__' method of the Person
class. That function, in turn, is creating a new Person instance, and
calling the '__init__' method of the newly-created instance. Finally,
the '__new__' method returns that instance back to the caller.

--
\ "Probably the toughest time in anyone's life is when you have |
`\ to murder a loved one because they're the devil." -- Emo |
_o__) Philips |
Ben Finney

Jeroen Ruigrok van der Werven

unread,
Jan 14, 2008, 6:21:09 AM1/14/08
to Fredrik Lundh, pytho...@python.org
-On [20080113 13:36], Fredrik Lundh (fre...@pythonware.com) wrote:
>given that they do different things, I'm not sure it's that helpful to
>describe them *both* as constructors.

I am still behind in my learning. ;)

To restate it more correctly: __init__ is akin to a constructor.

I am not entirely sure I fully understand __new__'s semantics though. The
first read-through of http://docs.python.org/ref/customization.html makes it
sound very similar to a call like: var = Object(arguments=...)

I must not be understanding something and __new__'s documentation there is not
that clear to me, to be honest.

--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/

I think, therefore I am...

Jeroen Ruigrok van der Werven

unread,
Jan 14, 2008, 6:24:18 AM1/14/08
to Ben Finney, pytho...@python.org
-On [20080113 14:03], Ben Finney (bignose+h...@benfinney.id.au) wrote:
>That's getting the two of them confused. __new__ is a constructor,
>__init__ is not.

And there I just sent an email stating the wrong thing.

I'll dig into it again, because I am really confusing something here (and
jumping between 4 languages on the same day is not helping much to be honest).

--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/

If slavery is not wrong, nothing is wrong...

Hrvoje Niksic

unread,
Jan 14, 2008, 6:53:30 AM1/14/08
to
Ben Finney <bignose+h...@benfinney.id.au> writes:

> What one is "in reality" calling is the '__new__' method of the Person
> class. That function, in turn, is creating a new Person instance, and
> calling the '__init__' method of the newly-created instance. Finally,
> the '__new__' method returns that instance back to the caller.

This is also not entirely correct. __new__ doesn't call __init__; if
it did, there would be no way to call __new__ without also calling
__init__ (pickle, among other things, does that and needs to do that
to correctly implement its logic).

"In reality" executing Person(...) invokes the __call__ method of
type(Person) (normally the standard metatype called "type") bound to
the Person type object. This is where the logic to call __new__
followed by __init__ is implemented, in code that does something close
to this:

obj = mytype.__new__(*args, **kwds)
if isinstance(obj, mytype):
mytype.__init__(obj, *args, **kwds)
return obj

Wildemar Wildenburger

unread,
Jan 14, 2008, 9:37:20 AM1/14/08
to
Jeroen Ruigrok van der Werven wrote:
> To restate it more correctly: __init__ is akin to a constructor.
>
No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a reply).

__init__() /initializes/ an instance (automatically after creation). It
is called, /after/ the instance has been constructed via the __new__()
method.
__new__() actually /constructs/ a new instance.


> I am not entirely sure I fully understand __new__'s semantics though.

Create a new (blank) instance of a class and return it. That's all there
is to it.


> I must not be understanding something and __new__'s documentation there is not
> that clear to me, to be honest.
>

It is somewhat confusing at first. But just bear in mind: 99 out of 100
times, you don't need to override __new__(). When you need it, you'll know.

/W

Hrvoje Niksic

unread,
Jan 14, 2008, 10:15:19 AM1/14/08
to
Wildemar Wildenburger <lasse...@klapptsowieso.net> writes:

> Jeroen Ruigrok van der Werven wrote:
>> To restate it more correctly: __init__ is akin to a constructor.
>>
> No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a
> reply).
>
> __init__() /initializes/ an instance (automatically after
> creation). It is called, /after/ the instance has been constructed

I don't understand the purpose of this "correction". After all,
__init__ *is* the closest equivalent to what other languages would
call a constructor. Take C++ and Java, the two most popular OO
languages in existence. Their constructors also "initialize" an
instance -- the actual allocation is left to the caller (new or stack
in C++) or to the garbage collector. They even share with Python the
convention of not returning the constructed value, they operate purely
on side effect, just like Python's __init__. And yet, no one says
that they are somehow not constructors because of that.

Wikipedia calls the constructor "a special method used in object
oriented programming which puts the object's members into a valid
state." Again, exactly what __init__ does.

Mel

unread,
Jan 14, 2008, 11:20:18 AM1/14/08
to
Hrvoje Niksic wrote:
> Wildemar Wildenburger <lasse...@klapptsowieso.net> writes:
>
>> Jeroen Ruigrok van der Werven wrote:
>>> To restate it more correctly: __init__ is akin to a constructor.
>>>
>> No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a
>> reply).
>>
>> __init__() /initializes/ an instance (automatically after
>> creation). It is called, /after/ the instance has been constructed
>
> I don't understand the purpose of this "correction". After all,
> __init__ *is* the closest equivalent to what other languages would
> call a constructor.

Nevertheless, __init__ doesn't construct anything. You can even call
it to reinitialize an existing object:


Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class AClass (object):
... def __init__ (self):
... self.a = 4
...
>>> a = AClass()
>>> a.a
4
>>> a.a = 5
>>> a.a
5
>>> a.__init__()
>>> a.a
4

Cheers, Mel.

Hrvoje Niksic

unread,
Jan 14, 2008, 11:29:16 AM1/14/08
to
Mel <mwi...@the-wire.com> writes:

>> I don't understand the purpose of this "correction". After all,
>> __init__ *is* the closest equivalent to what other languages would
>> call a constructor.
>
> Nevertheless, __init__ doesn't construct anything.

Only if by "construct" you mean "allocate". __init__ starts out with
an empty object and brings it to a valid state, therefore
"constructing" the object you end up with. That operation is exactly

Reedick, Andrew

unread,
Jan 14, 2008, 12:08:02 PM1/14/08
to Hrvoje Niksic, pytho...@python.org


Nah. Most other languages combine the constructor and an init function.
Normally with c++ I'll have the constructor call an Init() function so I
can re-initialize the object as needed. Python has explicitly split the
two.


Besides, the Python docs say that __new__ is the constructor and
__init__ may or may not be called after the instance is created:

__new__( cls[, ...])

Called to create a new instance of class cls. __new__() is a
static method (special-cased so you need not declare it as such) that
takes the class of which an instance was requested as its first
argument. The remaining arguments are those passed to the object
constructor expression (the call to the class). The return value of
__new__() should be the new object instance (usually an instance of
cls).

...
If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked
...
If __new__() does not return an instance of cls, then the new
instance's __init__() method will not be invoked.


__init__( self[, ...])

Called when the instance is created.
...
As a special constraint on constructors, no value may be
returned;

Also, how can a constructor require 'self' as an argument...?
__init__(self, ...)


If the __init__ function is called by the constructor it cannot return a
value. However if called as a normal function, it can return a value.
__init__ is just a function that gets called by the constructor, which
is __new__.


count = 0
class AClass (object):
def __init__ (self):
self.a = 4

global count
if count > 0:
return 'hello world'

count += 1


a = AClass()

print a.a
print a.__init__()


c:\foo\a.py>
4
hello world

*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA622


Neil Cerutti

unread,
Jan 14, 2008, 1:43:47 PM1/14/08
to pytho...@python.org
On Jan 14, 2008 12:08 PM, Reedick, Andrew <jr9...@att.com> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att...@python.org [mailto:python-
> > list-bounces+jr9445=att...@python.org] On Behalf Of Hrvoje Niksic
> > Sent: Monday, January 14, 2008 11:29 AM
> > Only if by "construct" you mean "allocate". __init__ starts out with
> > an empty object and brings it to a valid state, therefore
> > "constructing" the object you end up with. That operation is exactly
> > what other languages call a constructor.
>
> Nah. Most other languages combine the constructor and an init function.
> Normally with c++ I'll have the constructor call an Init() function so I
> can re-initialize the object as needed. Python has explicitly split the
> two.

> Besides, the Python docs say that __new__ is the constructor and
> __init__ may or may not be called after the instance is created:

The documentation of __new__ carefully refrains from calling __new__ a
constructor. Both __new__ and __init__ mention the object constructor
expression, e.g., "list()".

> __init__( self[, ...])
> Called when the instance is created.
> ...
> As a special constraint on constructors, no value may be
> returned;

Once again, the documentation is referring to constructor expressions.
As you noted, __init__ may return a value when not called by a
constructor expression.

C++'s constructor initialization lists are the closest thing to
Python's __new__. They can perform tasks for which Python might need
__new__. For example, a class member that's a reference must be
initialized in the initialization list, because it cannot be set once
the body of the constructor begins.

--
Neil Cerutti <mr.cerut...@gmail.com>

Hrvoje Niksic

unread,
Jan 14, 2008, 1:47:41 PM1/14/08
to
"Reedick, Andrew" <jr9...@att.com> writes:

>> Only if by "construct" you mean "allocate". __init__ starts out
>> with an empty object and brings it to a valid state, therefore
>> "constructing" the object you end up with. That operation is
>> exactly what other languages call a constructor.
>
> Nah. Most other languages combine the constructor and an init
> function.

Maybe so, but the standard term for what Python calls __init__ is
still "constructor".

> Also, how can a constructor require 'self' as an argument...?
> __init__(self, ...)

Think of it as the equivalent of Java's and C++'s "this", except it's
explicit in the argument list. "Explicit is better than implicit" and
all that. :-)

Steven D'Aprano

unread,
Jan 14, 2008, 4:21:43 PM1/14/08
to
On Mon, 14 Jan 2008 22:18:44 +1100, Ben Finney wrote:

> What one is "in reality" calling is the '__new__' method of the Person
> class. That function, in turn, is creating a new Person instance, and
> calling the '__init__' method of the newly-created instance. Finally,
> the '__new__' method returns that instance back to the caller.


But not if Person is an old-style class.


--
Steven

Ben Finney

unread,
Jan 14, 2008, 5:20:17 PM1/14/08
to
Hrvoje Niksic <hni...@xemacs.org> writes:

> Wildemar Wildenburger <lasse...@klapptsowieso.net> writes:
> > __init__() /initializes/ an instance (automatically after
> > creation). It is called, /after/ the instance has been constructed
>
> I don't understand the purpose of this "correction". After all,
> __init__ *is* the closest equivalent to what other languages would
> call a constructor.

No. That would be '__new__', which actually constructs the instance,
and actually returns it to the caller. '__init__' does neither of
those.

It so happens that, in Python, one usually overrrides the initialiser
and not the constructor. Thus, the confusion is understandable, but
still regrettable and avoidable.

--
\ "My, your, his, hers, ours, theirs, its. I'm, you're, he's, |
`\ she's, we're, they're, it's." —anonymous, |
_o__) alt.sysadmin.recovery |
Ben Finney

Hrvoje Niksic

unread,
Jan 14, 2008, 6:00:45 PM1/14/08
to
Ben Finney <bignose+h...@benfinney.id.au> writes:

> Hrvoje Niksic <hni...@xemacs.org> writes:
>
>> Wildemar Wildenburger <lasse...@klapptsowieso.net> writes:
>> > __init__() /initializes/ an instance (automatically after
>> > creation). It is called, /after/ the instance has been constructed
>>
>> I don't understand the purpose of this "correction". After all,
>> __init__ *is* the closest equivalent to what other languages would
>> call a constructor.
>
> No. That would be '__new__', which actually constructs the instance,

That's not what other OO languages (C++, Java) actually call a
constructor, so your correction is misplaced. My other posts in this
thread have expanded on this.

Steven D'Aprano

unread,
Jan 14, 2008, 10:44:25 PM1/14/08
to


How fortunate that Python isn't one of those other OO languages,
otherwise it might cause a bit of confusion.

--
Steven

Ben Finney

unread,
Jan 14, 2008, 11:24:52 PM1/14/08
to
Hrvoje Niksic <hni...@xemacs.org> writes:

> Ben Finney <bignose+h...@benfinney.id.au> writes:
>
> > Hrvoje Niksic <hni...@xemacs.org> writes:
> >> __init__ *is* the closest equivalent to what other languages
> >> would call a constructor.
> >
> > No. That would be '__new__', which actually constructs the
> > instance,
>
> That's not what other OO languages (C++, Java) actually call a
> constructor

More fool them, then. It seems that the best referent for the term
"constructor" is the thing that does the constructing and returns the
result.

--
\ "Imagine a world without hypothetical situations." -- Anonymous |
`\ |
_o__) |
Ben Finney

Bruno Desthuilliers

unread,
Jan 15, 2008, 5:06:47 AM1/15/08
to
Hrvoje Niksic a écrit :

> Ben Finney <bignose+h...@benfinney.id.au> writes:
>
>> Hrvoje Niksic <hni...@xemacs.org> writes:
>>
>>> Wildemar Wildenburger <lasse...@klapptsowieso.net> writes:
>>>> __init__() /initializes/ an instance (automatically after
>>>> creation). It is called, /after/ the instance has been constructed
>>> I don't understand the purpose of this "correction". After all,
>>> __init__ *is* the closest equivalent to what other languages would
>>> call a constructor.
>> No. That would be '__new__', which actually constructs the instance,
>
> That's not what other OO languages (C++, Java) actually call a
> constructor,

There are actually quite a few other OOPLs than C++ and Java, and at
least one of them (namely Smalltalk, which predates both C++ and Java)
uses distinct phases for allocation and initialisation.

IOW, it's not because C++ and/or Java use a given terminology that this
terminology should be blindly applied to each and every other OOPL.
FWIW, there are quite a lot of other differences between C++/Java and
Python when it comes to object model, and what OO is is definitively
*not* defined by C++ and/or Java.

So while it's true that __init__ is the closest equivalent to what C++
and Java (and possibly a couple "other languages") call a constructor,
it doesn't imply that you should refer to it as "the constructor". As
Neil Cerutti points out, there's in fact nothing like a 'constructor
method' in Python : there are a "__new__" method, an "__init__" method,
and "constructor expressions" which may invoke them !-)

Hrvoje Niksic

unread,
Jan 15, 2008, 5:15:18 AM1/15/08
to
Bruno Desthuilliers <bruno.42.de...@wtf.websiteburo.oops.com>
writes:

> So while it's true that __init__ is the closest equivalent to what
> C++ and Java (and possibly a couple "other languages") call a
> constructor, it doesn't imply that you should refer to it as "the
> constructor". As Neil Cerutti points out, there's in fact nothing
> like a 'constructor method' in Python : there are a "__new__"
> method, an "__init__" method, and "constructor expressions" which
> may invoke them !-)

I agree with this. The poster I was responding to called __init__
"akin to a constructor", which (to me) implied connection to other
languages, not aspiration to define __init__ as THE constructor.

Lie

unread,
Jan 15, 2008, 5:02:43 PM1/15/08
to
I've been in this Python mailing list for a few days, and I've noticed
several things here: There are too many fundamentalist!

Don't play stupid and all, don't be a fundamentalist. It might be true
that __init__ isn't a constructor and __new__ might be the constructor
(some people even claimed __new__ is also not a constructor).

From the base definition of a constructor: constructor is the creator
of an object. In this case, __new__ is technically the constructor
while __init__ is an initializer.

However, it is also to be noted that __init__ is what makes an object
meaningful, and that makes it a constructor in a sense (while still
technically a constructor). Without initialization, an object is
meaningless, even if the definition of the initializer is to leave it
as it is.

Python creates object by doing something like this:
a = anObject(arg1, arg2, arg3)

These arguments is then passed to __new__ and __init__ for their
arguments in its sake of creating and initializing the object. Then
anObject() returns an instance of anObject.

From an outsider's point of view, there is no difference between
__new__ and __init__ since they're "implementation details" (in other
languages, these are private functions[1] that is invisible to
outsiders, Python doesn't like privacy but the semantic of being
implementation detail still exist). For an outsider, there is
absolutely no need to know that __new__ and __init__ exists, they just
need to know anObject()'s arguments, which is the public view of the
constructor and initializer[2].

[1] Well, for fundamentalists: constructors aren't usually private
though, usually they're Friend or Protected Friend which prohibits
outsiders from calling it but allow other classes inheriting from it
to call them.
[2] In this sense, from outsider's POV anObject() is the constructor.


If you can't be convinced with this argument, then I'd give you
another that's a bit more Pythonic:
DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
like a duck, it is a duck!

From the class programmer's point of view, __init__ acts like an
object constructor in other languages, there is no significant
difference between __init__ and constructor in other languages. The
fact that __init__ works with side-effect as opposed to returning the
object is not a significant point and can be considered as an
implementation difference (I'm not aware of any major programming
language that returns an instance of itself in its return value
[except for Python]).

For example, in VB.NET, there is no doubt that Sub New() is a
constructor, despite New() works only by side effect, and returning
anything results in an error (since it is a Sub or a method in
Python's dictionary). Not only VB, C++ and C# also use side effect in
its constructors and doesn't return a value. In this sense, VB's New, C
++ constructor, and C# constructor is equal to Python's __init__, thus
the Duck Typing spirit applies here.

Reedick, Andrew

unread,
Jan 15, 2008, 5:34:16 PM1/15/08
to Lie, pytho...@python.org
> -----Original Message-----
> From: python-list-bounces+jr9445=att...@python.org [mailto:python-
> list-bounces+jr9445=att...@python.org] On Behalf Of Lie
> Sent: Tuesday, January 15, 2008 5:03 PM
> To: pytho...@python.org
> Subject: Re: __init__ explanation please
>
> I've been in this Python mailing list for a few days, and I've noticed
> several things here: There are too many fundamentalist!
>
> Don't play stupid and all, don't be a fundamentalist. It might be true
> that __init__ isn't a constructor and __new__ might be the constructor
> (some people even claimed __new__ is also not a constructor).

Purist is a better term. Fundamentalist is three syllables closer to
Holy War.


> >From the base definition of a constructor: constructor is the creator
> of an object. In this case, __new__ is technically the constructor
> while __init__ is an initializer.
>
> However, it is also to be noted that __init__ is what makes an object
> meaningful, and that makes it a constructor in a sense (while still
> technically a constructor). Without initialization, an object is
> meaningless, even if the definition of the initializer is to leave it
> as it is.


You don't need to have an __init__ defined. A subclass has to
explicitly call the parent's __init__ or the parent's __init__ is never
run. If the __init__ makes the object meaningful, then how meaningful
is an object without an __init__? I'm pretty sure that an object
without an __init__ is still a viable, working object.


> If you can't be convinced with this argument, then I'd give you
> another that's a bit more Pythonic:
> DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
> like a duck, it is a duck!


But you don't need __init__ to be a duck!


> >From the class programmer's point of view, __init__ acts like an
> object constructor in other languages, there is no significant
> difference between __init__ and constructor in other languages.


How many times can you call an object's constructor in other languages?
__init__ can be called repeatedly.


__init__ is the last straw that breaks the camel's back. Or rather, the
last method we see in the object creation process, and thus must be
'guilty' of being a constructor. Only a fundamentalist would blame the
victim instead of the real criminal, __new__.


We're splitting hairs. And I'm pretty sure that, aside from being a
spiffy thought experiment, no one cares as long as it works and makes
sense. =)


Repeated for clarity: smiley --> =) <-- smiley

*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA625


Steven D'Aprano

unread,
Jan 15, 2008, 8:02:55 PM1/15/08
to
On Tue, 15 Jan 2008 14:02:43 -0800, Lie wrote:

> I've been in this Python mailing list for a few days, and I've noticed
> several things here: There are too many fundamentalist!
>
> Don't play stupid and all, don't be a fundamentalist. It might be true
> that __init__ isn't a constructor and __new__ might be the constructor

It is true.


> (some people even claimed __new__ is also not a constructor).

They did? I must have missed them.


> From the base definition of a constructor: constructor is the creator of
> an object. In this case, __new__ is technically the constructor while
> __init__ is an initializer.

Yes, that is correct, although I too have been known to use "constructor"
to *informally* refer to __init__. It's a bad habit, and while
technically wrong, not always unforgivably wrong.


> However, it is also to be noted that __init__ is what makes an object
> meaningful, and that makes it a constructor in a sense (while still
> technically a constructor). Without initialization, an object is
> meaningless, even if the definition of the initializer is to leave it as
> it is.

Nope, not at all. The following class does not call the initializer:

class MyClass(object):
class __metaclass__(type):
def __call__(cls, *args, **kwargs):
obj = cls.__new__(cls)
print "There is no __init__."
return obj
def __new__(cls, *args, **kwargs):
print "This is the constructor, see me construct an instance!"
return object.__new__(cls)
def __init__(self, *args, **kwargs):
raise Exception("die die die!!!")


Now use it:

>>> c = MyClass()
This is the constructor, see me construct an instance!
There is no __init__.

And call the initializer by hand:

>>> c.__init__()


Traceback (most recent call last):

File "<stdin>", line 1, in ?
File "<stdin>", line 7, in __init__
Exception: die die die!!!


Here's a class with no constructor (or rather, a constructor that the
user *can't get to*):

class OldClass:
def __new__(cls, *args, **kwargs): # this is not called
raise Exception("die die die!!!")
def __init__(self, *args, **kwargs):
print "This is the initializer, see me initialize " \
"the already-constructed instance 'self'!"


>>> c = OldClass()
This is the initializer, see me initialize the already-constructed
instance 'self'!


For various reasons, Python splits the process of constructing and
initializing instances into two stages. What other languages do is
irrelevant. Perhaps Java and C++ don't need to distinguish between
"constructor" and "initializer", but Python does.

> Python creates object by doing something like this: a = anObject(arg1,
> arg2, arg3)

That's what the programmer does. Under the hood, Python does something
different.


> These arguments is then passed to __new__ and __init__ for their
> arguments in its sake of creating and initializing the object. Then
> anObject() returns an instance of anObject.

Assuming the standard metaclass.


> From an outsider's point of view, there is no difference between __new__
> and __init__ since they're "implementation details"

No, they most certainly are not implementation details. ANY
implementation of Python MUST use __new__ and __init__ or else it is not
Python, it is a different language. The nature of how Python creates
instances is part of the language specification, not the implementation.


> (in other languages,
> these are private functions[1] that is invisible to outsiders, Python
> doesn't like privacy but the semantic of being implementation detail
> still exist). For an outsider, there is absolutely no need to know that
> __new__ and __init__ exists, they just need to know anObject()'s
> arguments, which is the public view of the constructor and
> initializer[2].

I don't understand your argument. If you are saying that people who don't
care about the details of Python instance creation don't care about the
details of Python instance creation, then you're right, but it's a rather
pointless observation. Yes, people who don't care don't care.

But people who want to:

(1) Program successfully in Python;

(2) Compare how Python works to other computer languages;

(3) Do metaclass programming; or

(4) Find out how Python creates instances

will care about the details. Anybody asking for an explanation of
__init__ (like this thread!) is asking about the details. Why on earth do
you think it is a bad thing to answer the question accurately?


[snip]


> If you can't be convinced with this argument, then I'd give you another
> that's a bit more Pythonic:
> DUCK TYPING: If it looks like a duck, walks like a duck, and quacks like
> a duck, it is a duck!
>
> From the class programmer's point of view, __init__ acts like an object
> constructor in other languages, there is no significant difference
> between __init__ and constructor in other languages.

Fortunately, Python isn't those other languages. We're not discussing how
Java creates instances, or C++, or VisualBasic. We're discussing Python,
so any answer given that starts off "Well, in Java it works like this..."
is almost certainly going to be useless to the Python programmer asking
about Python.

[snip]


> In this sense, VB's New, C ++
> constructor, and C# constructor is equal to Python's __init__, thus the
> Duck Typing spirit applies here.

It isn't enough to quack like a duck. It also needs to walk like a duck
and swim like a duck too.

--
Steven

Lie

unread,
Jan 17, 2008, 12:55:44 PM1/17/08
to
On Jan 16, 5:34 am, "Reedick, Andrew" <jr9...@ATT.COM> wrote:
> > >From the base definition of a constructor: constructor is the creator
> > of an object. In this case, __new__ is technically the constructor
> > while __init__ is an initializer.
>
> > However, it is also to be noted that __init__ is what makes an object
> > meaningful, and that makes it a constructor in a sense (while still
> > technically a constructor). Without initialization, an object is
> > meaningless, even if the definition of the initializer is to leave it
> > as it is.
>
> You don't need to have an __init__ defined.  A subclass has to
> explicitly call the parent's __init__ or the parent's __init__ is never
> run.  

In other languages, constructor might be optional. In the case of non-
existent constructor, compilers would add an empty constructor, but
what's the difference (from programmer's POV) between Python ignoring
__init__ and other languages adding empty constructor? That's just an
implementation detail.

> If the __init__ makes the object meaningful, then how meaningful
> is an object without an __init__?  

It actually depends on the object, some objects might be pretty
meaningless without being initialized (or its members altered from
outside very carefully). Examples include a simple vector class. If
the vector is not initialized, the x and y equals None, which is not a
valid value for vector, which means the object is meaningless.

> I'm pretty sure that an object
> without an __init__ is still a viable, working object.

I'm sure it is, although it's initial value might not be a valid
value.

> > If you can't be convinced with this argument, then I'd give you
> > another that's a bit more Pythonic:
> > DUCK TYPING: If it looks like a duck, walks like a duck, and quacks
> > like a duck, it is a duck!
>
> But you don't need __init__ to be a duck!

lol...

> > >From the class programmer's point of view, __init__ acts like an
> > object constructor in other languages, there is no significant
> > difference between __init__ and constructor in other languages.
>
> How many times can you call an object's constructor in other languages?
> __init__ can be called repeatedly.

That's a very good argument to separate __init__ from a real
constructor, but how many projects you do would require object
recycling (which is the only reason I can think of for calling
initializers more than once)? Object recycling should only be done on
systems which lacks resources because it have big potential to
introduce bugs caused by incomplete cleaning.

> __init__ is the last straw that breaks the camel's back.  Or rather, the
> last method we see in the object creation process, and thus must be
> 'guilty' of being a constructor.  Only a fundamentalist would blame the
> victim instead of the real criminal, __new__.

It's not about blaming, rather they shared parts in the act.

> We're splitting hairs.  And I'm pretty sure that, aside from being a
> spiffy thought experiment, no one cares as long as it works and makes
> sense.   =)

I agree with that.

Reply all
Reply to author
Forward
0 new messages