473,414 Members | 1,626 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,414 software developers and data experts.

__init__ function problem

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
8 1740
"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
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

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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Martin Maney | last post by:
I've been to the cookbook (both forms, since they're sometimes usefully different), but that gave rise to more questions than answers. Heck, let me pull some of them up while I'm at it. ...
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...
2
by: Yin | last post by:
I've created a class that reads in and processes a file in the initializer __init__. The processing is fairly substantial, and thus, instead of processing the file every time the object is...
3
by: Sandro Dentella | last post by:
Hi everybody, I'm trying to fix the packaging of a very simple package, but some problem show me that I have not well understood the whole mechanism The structure of my package (some debug...
6
by: Rob Cowie | last post by:
Hi all, Is there a simple way to call every method of an object from its __init__()? For example, given the following class, what would I replace the comment line in __init__() with to result...
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. ...
4
by: Noah | last post by:
Am I the only one that finds the super function to be confusing? I have a base class that inherits from object. In other words new style class: class foo (object): def __init__ (self, arg_A,...
16
by: John Salerno | last post by:
Let's say I'm making a game and I have this base class: class Character(object): def __init__(self, name, stats): self.name = name self.strength = stats self.dexterity = stats...
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...
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: 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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.