Adding a method to an instance

Kirby Urner urner at alumni.princeton.edu
Sat Mar 3 02:18:46 EST 2001


Kirby Urner <urner at alumni.princeton.edu> 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.

Kirby




More information about the Python-list mailing list