Adding a method to an instance
urner at alumni.princeton.edu
Sat Mar 3 08:18:46 CET 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:
self.message = msg
>>> o = test()
>>> o.prn("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'
' trying again'
['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