Adding a method to an instance

Kirby Urner urner at
Sat Mar 3 07:06:46 CET 2001

Bryan Mongeau <bryan at> wrote:

>Quick one for you guys:
>I would like to add a method to an instantiated class. 
>class foo:
>  def __init__(self):
> = 123
>f = foo()
>Now to add a method to the instance f of class foo:
>def newMethod(self):
>  print
>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
 < instance at 00B9719C>
 >>> k = lambda x: x+2
 >>> k(2)
 >>> o.othermethod = k
 >>> o.othermethod(3)
 >>> dir(o)
 >>> dir(foo)
 ['__doc__', '__module__', 'duh']
 >>> o.__class__
 <class at 00BB3ECC>
 >>> foo
 <class at 00BB3ECC>
 >>> o
 < 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.


More information about the Python-list mailing list