Adding a method to an instance
Kirby Urner
urner at alumni.princeton.edu
Sat Mar 3 01:06:46 EST 2001
Bryan Mongeau <bryan at eevolved.com> wrote:
>Quick one for you guys:
>
>I would like to add a method to an instantiated class.
>
>class foo:
> def __init__(self):
> self.bar = 123
>
>f = foo()
>
>Now to add a method to the instance f of class foo:
>
>def newMethod(self):
> print self.bar
>
>f.__class__.newMethod = newMethod
In saying f.__class__, you point back to the superclass foo.
If you want to poke newMethod into object f alone, then you
should just go:
f = newMethod
Here's a transcript that addresses your question:
>>> class foo:
def duh(self):
print "Duh!"
>>> o = foo()
>>> o
<__main__.foo instance at 00B9719C>
>>> k = lambda x: x+2
>>> k(2)
4
>>> o.othermethod = k
>>> o.othermethod(3)
5
>>> dir(o)
['othermethod']
>>> dir(foo)
['__doc__', '__module__', 'duh']
>>> o.__class__
<class __main__.foo at 00BB3ECC>
>>> foo
<class __main__.foo at 00BB3ECC>
>>> o
<__main__.foo instance at 00B9719C>
Note re the last three commands: o.__class__ is a pointer to
the class foo in memory, so you would be adding to the superclass
to put a method in there. You want to insert your method into
the instance/object, so don't involve its __class__.
I bet you get it now.
Kirby
More information about the Python-list
mailing list