Adding a method to an instance

Jay O'Connor joconnor at
Sat Mar 3 16:48:58 CET 2001

On Sat, 03 Mar 2001 05:12:06 GMT, Bryan Mongeau <bryan at>

>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
>This works, except that it modifies the definition of class foo!
>>>> dir(foo)
>['__doc__', '__init__', '__module__']
>>>> f.__class__.newMethod = newMethod
>>>> f.newMethod()
>>>> dir(foo)
>['__doc__', '__init__', '__module__', 'newMethod']
>Is there a way to add the method only to the instance?  Oh, and please 
>don't ask me *why* I want to do this. Just trust me :)

You can use the module 'new' to create a new instance method for an

>>> import new
>>>class foo:
	def __init__(self): = 123

>>>f = foo()

>>> def newMethod (self):

>>>f.newMethod = new.instancemethod (newMethod, f, foo)


>>> g = foo()
>>> g.newMethod()
Traceback (innermost last):
  File "<pyshell#16>", line 1, in ?
AttributeError: 'foo' instance has no attribute 'newMethod'

Notice that f has the newMethod, but it only applies to f, g does not
get the new method

Jay O'Connor
joconnor at

Python Language Discussion Forum -

"God himself plays on the bass strings first, when he tunes the soul"

More information about the Python-list mailing list