[Tutor] __init__

Alan Trautman ATrautman@perryjudds.com
Thu Feb 27 15:08:02 2003


Vicki,

This is one of the hardest things to get in programming but also the best
once you figure out how. I'll try to give an example.

class Circle:
    
    def __init__(self,radius):
        if radius > 0 :
            self.radius = radius
        else:
            print "invalid radius"
            self.radius = 1
        
        self.pi = 3.14
        
    def circumference_calc (self):
        circ = self.pi * self.radius * self.radius
        print 'The circumference is ', circ

if __name__ == '__main__':
    print 'testing'
    c = Circle(3)
    c.circumference_calc()
    c = Circle(-3)
    c.circumference_calc()

You'll see that the __init__ property verifies the data and sets all values
needed to ensure the class functions properly in all cases. In my example
that radius is set to a positive value and that a safe default value is
inserted if it is not. This is not usually necessary as unchecked values
should never be used to create a class. In the other I create a value that
will be used within the class and set its value. Esstentially the __init__
block ensures that with no other support this class will function properly
even though it will not generate the values expected. It will also give an
error is someone attempts to use a class without giving it the proper
elements( arguements formally).

HTH
Alan

-----Original Message-----
From: vicki@stanfield.net [mailto:vicki@stanfield.net]
Sent: Thursday, February 27, 2003 10:19 AM
To: tutor@python.org
Subject: [Tutor] __init__


I think I am missing some very basic knowledge with
regard to my Python/Tkinter programming which is
preventing me from understanding the examples that I
find. First the __init__ part, when do I need one? I
notice that most of the modules that I include contain
one. Also the example that I am trying to use to make
my callback (for a Pmw.Entrybox) includes one. Can
someone point me to some clear definition of what it is
and when I need it. I apologize for being dense, but I
can't seem to get past this.

Thanks,
--vicki

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor