__init__ function problem

K

kelin,zzf818

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!
 
D

Duncan Booth

kelin said:
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.
 
S

Steven D'Aprano

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

babui

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")
 
C

Carl Banks

kelin said:
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
 
J

Jia Lu

In Python, the real constructor is called __new__, >
Carl Banks

But the code below won't invoke __new__:

Code:
class Test:
    def __new__(self, value):
        print "__new__",value
    def __init__(self,value):
        print "__init__",value

x = Test("testing")
 
G

Gabriel Genellina

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
 
K

kelin,zzf818

Hi,
I've read all of this. And I am clear about it.
Thanks all.
Best Regards!
 
C

Colin J. Williams

Carl said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top