By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,645 Members | 1,047 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

__init__ function problem

P: n/a
Hi,

Today I read the following sentences, but I can not understand what
does the __init__ method of a class do?
__init__ is called immediately after an instance of the class is
created. It would be tempting but incorrect to call this the
constructor of the class. It's tempting, because it looks like a
constructor (by convention, __init__ is the first method defined for
the class), acts like one (it's the first piece of code executed in a
newly created instance of the class), and even sounds like one ("init"
certainly suggests a constructor−ish nature). Incorrect, because the
object has already been constructed by the time __init__ is called, and
you already have a valid reference to the new instance of the class.
But __init__ is the closest thing you're going to get to a constructor
in Python, and it fills much the same role.

It says the __init__ is called immediately after an instance of the
class is created. What dose "immediately" mean?
And what is difference between the init method and the constructor in
Java?

Thanks a lot!

Nov 7 '06 #1
Share this Question
Share on Google+
8 Replies


P: n/a
"kelin,zz****@gmail.com" <zz****@gmail.comwrote:
Today I read the following sentences, but I can not understand what
does the __init__ method of a class do?
__init__ is called immediately after an instance of the class is
created. It would be tempting but incorrect to call this the
constructor of the class. It's tempting, because it looks like a
constructor (by convention, __init__ is the first method defined for
the class), acts like one (it's the first piece of code executed in a
newly created instance of the class), and even sounds like one ("init"
certainly suggests a constructor−ish nature). Incorrect, because the
object has already been constructed by the time __init__ is called, and
you already have a valid reference to the new instance of the class.
But __init__ is the closest thing you're going to get to a constructor
in Python, and it fills much the same role.
I don't know where you read that, but it is wrong (or at least out of
date). The closest thing you are going to get to a constructor in Python is
actually the constructor '__new__'. Mostly though you don't need to worry
about __new__ in Python.
>
It says the __init__ is called immediately after an instance of the
class is created. What dose "immediately" mean?
It means that when you call:

x = SomeClass()

the interpreter first calls the constructor SomeClass.__new__, and then
immediately calls the initialiser SomeClass.__init__ on the newly created
object, and after that it returns the newly created object.

A constructor creates an object and returns it, an initialiser initialises
an existing object and does not return anything.

The constructor has the power to control how the memory for the object is
allocated (e.g. in Python it could return an already existing object
instead of creating a new one, but in that case the initialiser will be
called again on the existing object).

The initialiser usually sets up the attributes on a newly created object,
but for immutable objects (e.g. tuple) the attributes must be set by the
constructor.
Nov 7 '06 #2

P: n/a
On Tue, 07 Nov 2006 05:26:07 -0800, kelin,zz****@gmail.com wrote:
Hi,

Today I read the following sentences, but I can not understand what
does the __init__ method of a class do?
Play around with this class and see if it helps:
class MagicStr(str):
"""Subclass of str with leading and trailing asterisks."""
def __new__(cls, value=''):
print "Calling subclass constructor __new__ ..."
# Construct a MagicStr object.
obj = super(MagicStr, cls).__new__(cls, '***' + value + '***')
print " - inspecting constructor argument:"
print " value, id, type:", value, id(value), type(value)
print " - inspecting constructor result:"
print " value, id, type:", obj, id(obj), type(obj)
# Create the instance, and call its __init__ method.
return obj
def __init__(self, value):
print "Calling subclass __init__ ..."
print " - inspecting __init__ argument:"
print " value, id, type:", value, id(value), type(value)
print "Done."
Notice that when __new__ is called, the instance doesn't exist yet, only
the class, so the first argument for __new__ is the class, not the
instance.
__init__ is called immediately after an instance of the class is
created. It would be tempting but incorrect to call this the
constructor of the class. It's tempting, because it looks like a
constructor (by convention, __init__ is the first method defined for
the class), acts like one (it's the first piece of code executed in a
newly created instance of the class),
That's not quite true. For new-style classes __new__ is called before
__init__, as you can see from the MagicStr class above.

and even sounds like one ("init"
certainly suggests a constructor-ish nature). Incorrect, because the
object has already been constructed by the time __init__ is called, and
you already have a valid reference to the new instance of the class.
But __init__ is the closest thing you're going to get to a constructor
in Python, and it fills much the same role.
This is true for old-style classes.
It says the __init__ is called immediately after an instance of the
class is created. What dose "immediately" mean?
Once the __new__ method creates the instance and returns, before anything
else happens, the instance's __init__ method is called.

--
Steven.

Nov 7 '06 #3

P: n/a

Steven D'Aprano ha escrit:
Once the __new__ method creates the instance and returns, before anything
else happens, the instance's __init__ method is called.
This only happens when the object created by __new__ isinstance of the
class invoked in the creation statement, that is:

s=MagicStr("lala")

executes:

s = MagicStr.__new__(MagicStr, "lala")
if isinstance(s, MagicStr):
type(s).__init__(s, "lala")

--
Juan M. Gimeno

Nov 7 '06 #4

P: n/a
kelin,zz****@gmail.com wrote:
It says the __init__ is called immediately after an instance of the
class is created. What dose "immediately" mean?
And what is difference between the init method and the constructor in
Java?
For all intents and purposes, __init__ is a constructor. It isn't
technically, but you use it exactly the same way you use constructors
in C++ and Java (well, acutally, Python __init__ is a quite bit more
flexible, though also less convenient in many cases). Don't worry that
it isn't called a constructor.

In Python, the real constructor is called __new__, but you shouldn't
use __new__ like C++ and Java constructors. Usually there's no reason
to use __new__ at all. (The main use case is to return something other
than a newly created object, such as a preallocated or cached object.
For your normally functioning classes, you should use __init__.)
Carl Banks

Nov 7 '06 #5

P: n/a
In Python, the real constructor is called __new__, >
Carl Banks
But the code below won't invoke __new__:

Expand|Select|Wrap|Line Numbers
  1. class Test:
  2. def __new__(self, value):
  3. print "__new__",value
  4. def __init__(self,value):
  5. print "__init__",value
  6.  
  7. x = Test("testing")
  8.  
Nov 8 '06 #6

P: n/a
At Tuesday 7/11/2006 21:47, Jia Lu wrote:
In Python, the real constructor is called __new__, >
Carl Banks

But the code below won't invoke __new__:
Is this a question, or just for making things more and more confusing
to beginners?
>class Test:
def __new__(self, value):
print "__new__",value
For old-style classes __new__ is not used. On new-style classes it's
used mostly for dealing with immutable objects. The code should be:

class NewStyle(object):
"A new style class inherits from object in some way"
def __new__(cls, value):
print "NewStyle.__new__",value
return super(NewStyle, cls).__new__(cls, value)
# return object.__new__(cls, value) for lazy people

def __init__(self, value):
print "NewStyle.__init__",value

class OldStyle:
"An old style class does not inherit from object"
def __init__(self, value):
print "OldStyle.__init__",value

n = NewStyle(1)
o = OldStyle(2)
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 8 '06 #7

P: n/a
Hi,
I've read all of this. And I am clear about it.
Thanks all.
Best Regards!

Gabriel Genellina wrote:
At Tuesday 7/11/2006 21:47, Jia Lu wrote:
In Python, the real constructor is called __new__, >
Carl Banks
But the code below won't invoke __new__:

Is this a question, or just for making things more and more confusing
to beginners?
class Test:
def __new__(self, value):
print "__new__",value

For old-style classes __new__ is not used. On new-style classes it's
used mostly for dealing with immutable objects. The code should be:

class NewStyle(object):
"A new style class inherits from object in some way"
def __new__(cls, value):
print "NewStyle.__new__",value
return super(NewStyle, cls).__new__(cls, value)
# return object.__new__(cls, value) for lazy people

def __init__(self, value):
print "NewStyle.__init__",value

class OldStyle:
"An old style class does not inherit from object"
def __init__(self, value):
print "OldStyle.__init__",value

n = NewStyle(1)
o = OldStyle(2)
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 8 '06 #8

P: n/a
Carl Banks wrote:
kelin,zz****@gmail.com wrote:
>It says the __init__ is called immediately after an instance of the
class is created. What dose "immediately" mean?
And what is difference between the init method and the constructor in
Java?

For all intents and purposes, __init__ is a constructor. It isn't
technically, but you use it exactly the same way you use constructors
in C++ and Java (well, acutally, Python __init__ is a quite bit more
flexible, though also less convenient in many cases). Don't worry that
it isn't called a constructor.

In Python, the real constructor is called __new__, but you shouldn't
use __new__ like C++ and Java constructors. Usually there's no reason
to use __new__ at all. (The main use case is to return something other
than a newly created object, such as a preallocated or cached object.
For your normally functioning classes, you should use __init__.)
numpy.ndarray is an exception. There, one must call __new__, or a
factory function which does the same thing.

Colin W.
>

Carl Banks
Nov 8 '06 #9

This discussion thread is closed

Replies have been disabled for this discussion.