Adding a method to an instance
Jay O'Connor
joconnor at cybermesa.com
Sat Mar 3 10:48:58 EST 2001
On Sat, 03 Mar 2001 05:12:06 GMT, 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
>
>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 :)
>
You can use the module 'new' to create a new instance method for an
object
>>> import new
>>>class foo:
def __init__(self):
self.bar = 123
>>>f = foo()
>>> def newMethod (self):
print self.bar
>>>f.newMethod = new.instancemethod (newMethod, f, foo)
>>>f.newMethod()
123
>>> g = foo()
>>> g.newMethod()
Traceback (innermost last):
File "<pyshell#16>", line 1, in ?
g.newMethod()
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 cybermesa.com
http://www.cybermesa.com/~joconnor
Python Language Discussion Forum - http://pub1.ezboard.com/fobjectorienteddevelopmentpython
"God himself plays on the bass strings first, when he tunes the soul"
More information about the Python-list
mailing list