Dynamic method

Lawrence Oluyede raims at dot.com
Mon Jul 16 08:41:43 EDT 2007


Bruno Desthuilliers <bruno.42.desthuilliers at wtf.websiteburo.oops.com>
wrote:
> > I agree that in general the solution explained by Alex and you is better.
> 
> They are not "better" - they are correct.

Another way is to use the 'types' module:

In [1]: class T(object):
   ...:     pass
   ...: 

In [2]: t = T()

In [3]: import types

In [5]: types.MethodType?
Type:           type
Base Class:     <type 'type'>
String Form:    <type 'instancemethod'>
Namespace:      Interactive
Docstring:
    instancemethod(function, instance, class)
    
    Create an instance method object.


In [10]: m = types.MethodType(lambda self: 3, t, T)

In [11]: t.m = m

In [12]: t.m()
Out[12]: 3


-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair



More information about the Python-list mailing list