How to replace an instance method?

Eryk Sun eryksun at gmail.com
Mon Sep 19 17:05:33 EDT 2022


On 9/19/22, 2QdxY4RzWzUUiLuE at potatochowder.com
<2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
> On 2022-09-18 at 09:11:28 +0000,
> Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>
>> ram at zedat.fu-berlin.de (Stefan Ram) writes (abbreviated):
>> >types.MethodType( function, instance )
>> >functools.partial( function, instance )
>> >new_method.__get__( instance )
>>
>>   I wonder which of these three possibilities expresses
>>   the idea of creating a new method from a function and
>>   an instance most clearly.
>
> The first one.  And only the first one.
>
> The second one requires too much inside knowledge of Python to make the
> leap from currying to instance method.
>
> The third one doesn't even mention the function.

The OP's example named the function "new_method". In general the third
case would be func.__get__(instance). It's how the interpreter binds a
new method when a function from the class hierarchy is accessed as an
instance attribute.

When a function from the class hierarchy is accessed as an attribute
of the class, it's equivalent to calling func.__get__(None, cls),
which just returns a reference to the function. To use the descriptor
protocol to bind a function as a method of the class requires wrapping
it with the classmethod descriptor type. For example,
classmethod(func).__get__(None, cls) returns a method object with
__self__ that references the cls type. Of course, calling
types.MethodType(func, cls) is easier to understand and the preferred
way.


More information about the Python-list mailing list