473,385 Members | 2,029 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,385 software developers and data experts.

__init__ explanation please

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
Jan 13 '08 #1
25 2473
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.
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
Jan 13 '08 #2
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. 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

You don't always need __init__ if
__new__ is used with a "new" class.

Colin W.

Jan 13 '08 #3
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"?
Jan 13 '08 #4
-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.
Jan 13 '08 #5
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>

Jan 13 '08 #6
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>

Jan 13 '08 #7
Jeroen Ruigrok van der Werven <as*****@in-nomine.orgwrites:
-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
Jan 13 '08 #8
On 2008-01-13, Erik Lind <el***@spamcop.netwrote:
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.
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
Jan 14 '08 #9
"A.T.Hofkamp" <ha*@se-162.se.wtb.tue.nlwrites:
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
Jan 14 '08 #10
-On [20080113 14:03], Ben Finney (bi****************@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...
Jan 14 '08 #11
Ben Finney <bi****************@benfinney.id.auwrites:
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
Jan 14 '08 #12
Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
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.
Jan 14 '08 #13
Mel
Hrvoje Niksic wrote:
Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
>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.
Jan 14 '08 #14
Mel <mw*****@the-wire.comwrites:
>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
what other languages call a constructor.
Jan 14 '08 #15
"Reedick, Andrew" <jr****@att.comwrites:
>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. :-)
Jan 14 '08 #16
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
Jan 14 '08 #17
Hrvoje Niksic <hn*****@xemacs.orgwrites:
Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
__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
Jan 14 '08 #18
Ben Finney <bi****************@benfinney.id.auwrites:
Hrvoje Niksic <hn*****@xemacs.orgwrites:
>Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
__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.
Jan 14 '08 #19
On Tue, 15 Jan 2008 00:00:45 +0100, Hrvoje Niksic wrote:
Ben Finney <bi****************@benfinney.id.auwrites:
>Hrvoje Niksic <hn*****@xemacs.orgwrites:
>>Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
__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.

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

--
Steven
Jan 15 '08 #20
Hrvoje Niksic <hn*****@xemacs.orgwrites:
Ben Finney <bi****************@benfinney.id.auwrites:
Hrvoje Niksic <hn*****@xemacs.orgwrites:
__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
Jan 15 '08 #21
Hrvoje Niksic a écrit :
Ben Finney <bi****************@benfinney.id.auwrites:
>Hrvoje Niksic <hn*****@xemacs.orgwrites:
>>Wildemar Wildenburger <la*********@klapptsowieso.netwrites:
__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 !-)
Jan 15 '08 #22
Bruno Desthuilliers <br********************@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.
Jan 15 '08 #23
Lie
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.
Jan 15 '08 #24
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

Jan 16 '08 #25
Lie
On Jan 16, 5:34*am, "Reedick, Andrew" <jr9...@ATT.COMwrote:
>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.
Jan 17 '08 #26

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

Similar topics

3
by: achan | last post by:
As I was trying to create a metaclass, I found out that __init__ defined in it does not initializes at all: class CMeta(type): def __new__(cls, ClassName, BaseClass, ClassDict): def...
4
by: Justin | last post by:
On the advice of some members of this group I have decided to post a very specific question / problem with a code example. My problem is that my wxWidgets are created in the __init__ function of a...
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...
13
by: scott | last post by:
hi people, can someone tell me, how to use a class like that* (or "simulate" more than 1 constructor) : #-- class myPointClass: def __init__(self, x=0, y=0): self.x = x self.y = y def...
3
by: Iyer, Prasad C | last post by:
I am new to python. I have few questions a. Is there something like function overloading in python? b. Can I overload __init__ method Thanks in advance regards
10
by: ryanshewcraft | last post by:
Let me start with my disclaimer by saying I'm new to computer programming and have doing it for the past three weeks. I may not be completely correct with all the jargon, so please bear with me. ...
2
by: flogic | last post by:
Hi i m a newbie to python .. jus started to learn ...am quite confused about variable arguments used in python functions and in init. i dont where to use **keys , **kwds,*args ...etc... if...
19
by: dickinsm | last post by:
Here's an example of a problem that I've recently come up against for the umpteenth time. It's not difficult to solve, but my previous solutions have never seemed quite right, so I'm writing to...
4
by: Steven D'Aprano | last post by:
When you call a new-style class, the __new__ method is called with the user-supplied arguments, followed by the __init__ method with the same arguments. I would like to modify the arguments...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.