Adding a method to an instance

Bryan Mongeau bryan at eevolved.com
Sat Mar 3 00:12:06 EST 2001


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

This works, except that it modifies the definition of class foo!

>>> dir(foo)
['__doc__', '__init__', '__module__']
>>> f.__class__.newMethod = newMethod
>>> f.newMethod()
123
>>> 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 :)

Regards,
-- 
<=====================================>
Bryan Mongeau
Lead Developer, Director
eEvolved Real-Time Technologies Inc.
Website:    http://www.eevolved.com
Public key: http://eevolved.com/bcm.pk
<=====================================>

"The eternal mystery of the world is its comprehensibility."-- Einstein




More information about the Python-list mailing list