473,666 Members | 2,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__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 2497
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("oop s! 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.orgwrite s:
-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.h tml>

__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
"initialise r" 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.Hofkam p" <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

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

Similar topics

3
2588
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 __init__(self): for k in self.__slots__: k = 'something' NewDict = {'__slots__': , '__init__': __init__} for k in ClassDict:
4
1864
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 panel. (This is the way wx demos showed, I am brand new so I copies what they did) my problem is now it appears that my widgets are completely encapsulated within this __init__ class and I cannot get at them. Here is an example of me trying to...
9
6203
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 nonetheless, so that the instance is initialized a second time. For example, please consider the following class (a singleton in this case): >>> class C(object): .... instance = None .... def __new__(cls): .... if C.instance is None:
13
2604
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 __init__(self, x=0, y=0, z=0):
3
2885
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
1677
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. Anyways, I'm writing a function which has a class called "MultipleRegression." I want one of the variables under the __init__ method to be a list. I've got: class MultipleRegression: def __init__(self, dbh, regressors, fund):
2
2690
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 anyone culd give some explanation with examples or clear detailed web link, it wuld be helpful to me
19
1625
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 ask whether others have encountered this problem, and if so what solutions they've come up with. Suppose you're writing a class "Rational" for rational numbers. The __init__ function of such a class has two quite different roles to play. ...
4
3534
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 after the __new__ method is called but before the __init__ method, somewhat like this: .... def __new__(cls, *args): .... print "__new__", args
0
8449
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8360
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8876
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8784
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8556
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8642
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2774
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.