Adding a method to an instance

Kirby Urner urner at
Sat Mar 3 08:18:46 CET 2001

Kirby Urner <urner at> wrote:

Or here's a variation you may prefer -- I don't know your
context, but in this one, we just hard-code the name of 
the instance and therefore don't even bother to pass it 
as a parameter:

  >>> class test:
	def prn(self,msg):
	   self.message = msg
	   print msg

  >>> o = test()
  >>> o.prn("1-2-3 testing")
  1-2-3 testing
  >>> o.message
  '1-2-3 testing'
  >>> def newMethod(newtext):
	o.added = newtext
	return o.message + newtext

  >>> o.newMethod = newMethod
  >>> o.newMethod(" trying again")
  '1-2-3 testing trying again'
  >>> o.added
  ' trying again'
  >>> dir(o)
  ['added', 'message', 'newMethod']

I think I like the first example better.  Maybe others
will offer yet more ways to skin the snake.


More information about the Python-list mailing list