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

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

Reply via email to