[Tutor] Explain to me Initializing

Alan Gauld alan.gauld at btinternet.com
Sun Jan 16 02:18:21 CET 2011


"walter weston" <hacker0100 at hotmail.com> wrote in message 
news:BLU151-w4251D1FB9896DC3F8266C5D8F20 at phx.gbl...

Please explain to me what initializing is,like when you _init_
a function or class . what is _init_ and what does it really do ?

First you don;t init a function, you can init an object.
Initializing means setting up the data ready to do work.
Its a bit like filling your car with fuel before going on a journey.
If there is no fuel the car won't work.

Similarly with an object, if the initial values have not been
set up properly you will get wrong results. Take a very simple
object - a toggle switch. You need to know whether the switch
is currently on or off. and you need to toggle it to the
opposite setting.

But before you can start doing anything you need to set
the initial value to either on or off. Otherwise the toggle
option makes no sense.

class ToggleSwitch:
      def switch(self):
           if self.state == 'on':
              self.state= 'off'
           else: self.state = 'on'
           return self.state

ts = ToggleSwitch()
print ts.state
print ts.switch()

This code will fail because we have not created a valid
variable state which is needed fotr the switch function
to work. So we need to initialise the object:

class ToggleSwitch:
      def __init__(self):
           self.state = 'off'

      def switch(self):
           if self.state == 'on':
              self.state= 'off'
           else: self.state = 'on'
           return self.state

ts = ToggleSwitch()
print ts.state
print ts.switch()

Now it should work... (but its late so I haven't tested it!)


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list