I\'ve read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.
I understand that it\'s not always good to do so
There are at least two ways for attach a method to an instance without types.MethodType
:
>>> class A:
... def m(self):
... print 'im m, invoked with: ', self
>>> a = A()
>>> a.m()
im m, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.m
>
>>>
>>> def foo(firstargument):
... print 'im foo, invoked with: ', firstargument
>>> foo
1:
>>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))
>>> a.foo()
im foo, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.foo
>
2:
>>> instancemethod = type(A.m)
>>> instancemethod
>>> a.foo2 = instancemethod(foo, a, type(a))
>>> a.foo2()
im foo, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.foo2
>
Useful links:
Data model - invoking descriptors
Descriptor HowTo Guide - invoking descriptors