__init__ explanation please

Daniel Fetchinson fetchinson at googlemail.com
Sat Jan 12 19:56:09 EST 2008


> 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



More information about the Python-list mailing list