[Tutor] Re: Help with classes (Joseph Q.)

Kent Johnson kent37 at tds.net
Sat Apr 9 21:54:01 CEST 2005


Joseph Quigley wrote:
> class Message:
>   def init(self, p = 'Hello world'):
>      self.text = p
>   def sayIt(self):
>      print self.text
> 
> m = Message()
> m.init()
> m.sayIt()
> m.init('Hiya fred!')
> m.sayIt()

This is OK but a more conventional usage is to write an __init__() method. This is sometimes called 
a constructor and it is called automatically when you make a new class instance. Using __init__() 
your example would look like this:

class Message:
   def __init__(self, p = 'Hello world'):
      self.text = p
   def sayIt(self):
      print self.text

m = Message()
m.sayIt()
m = Message('Hiya fred!')
m.sayIt()

though this is nemantically a little different than yours because I create a new Message with the 
new string while you reuse the old one.

Kent



More information about the Tutor mailing list