Dynamic class methods misunderstanding
Christos TZOTZIOY Georgiou
tzot at sil-tec.gr
Mon Jan 31 06:01:42 EST 2005
On Sat, 29 Jan 2005 10:24:27 +0100, rumours say that aleaxit at yahoo.com
(Alex Martelli) might have written:
>Bill Mill <bill.mill at gmail.com> wrote:
>> > class Test:
>> > def __init__(self, method):
>> > self.m = new.instancemethod(method, self, Test)
>> Beautiful! thank you very much. Looking into the "new" module in
>> python 2.4, that's equivalent to:
>> self.m = type(self.__init__)(method, self, Test)
>Another approach with the same result is to exploit the fact that a
>function is a descriptor:
>self.m = method.__get__(self, Test)
Almost true; not all builtin functions are descriptors though.
.>> import new
.>> f= new.instancemethod(divmod, 7, object)
.>> map(f, range(1,10,2))
[(7, 0), (2, 1), (1, 2), (1, 0), (0, 7)]
.>> f= divmod.__get__(7)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
AttributeError: 'builtin_function_or_method' object has no attribute
I didn't run an extensive test, but it's possible that all builtin
functions are not descriptors.
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
More information about the Python-list