Adding a method to an instance

RajGopal Srinivasan raj at grserv.med.jhmi.edu
Sat Mar 3 04:19:57 EST 2001


Here is an attempt.  I am completely unsure of what the problems with
this
approach are, but here it goes

>>> class A:
...     def __init__(self):
...             self.value = 2
... 
>>> a = A()
>>> 
>>> def func():
...     self.value = self.value + 2
... 
>>> # the ugly part
... 
>>> func.func_globals['self'] = a
>>> 
>>> a.func = func
>>> 
>>> a.func()
>>> print a.value
4
>>> dir(A)
['__doc__', '__init__', '__module__']
>>> dir(a)
['func', 'value']

raj



More information about the Python-list mailing list