User Method CAN be based on built-in function!?

Alex Martelli aleaxit at yahoo.com
Thu Aug 2 05:23:33 EDT 2001


"Tom" <tom-list at home.com> wrote in message news:3b688229_5 at Usenet.com...
> I find this odd.
>
> In my experiments with Python 2.1.1 on Windows 2000, a user-defined method
> can be based on a 'builtin function'.
>
> In other words, I call PyObject_GetAttrString( pPyObject, "im_func" ),
> and a built-in function type object is returned.
>
> How can this be?

Pretty easily!  new.instancemethod(callable, instance_or_None, klass)
accepts any callable as its first argument.  So, for example:

class X:
    def __len__(self): return 23

import new
X.plik = new.instancemethod(len, None, X)

Now any instance x of X has a method x.plik() [returning 23] and
x.pak.im_func is len, the well-known builtin.


Alex






More information about the Python-list mailing list