How to replace an instance method?

Chris Angelico rosuav at gmail.com
Sat Sep 17 17:27:19 EDT 2022


On Sun, 18 Sept 2022 at 07:20, Ralf M. <Ralf_M at t-online.de> wrote:
>
> Am 16.09.2022 um 23:34 schrieb Eryk Sun:
> > On 9/16/22, Ralf M. <Ralf_M at t-online.de> wrote:
> >> I would like to replace a method of an instance, but don't know how to
> >> do it properly.
> >
> > A function is a descriptor that binds to any object as a method. For example:
> >
> >      >>> f = lambda self, x: self + x
> >      >>> o = 42
> >      >>> m = f.__get__(o)
> >      >>> type(m)
> >      <class 'method'>
> >      >>> m.__self__ is o
> >      True
> >      >>> m(10)
> >      52
>
> Thank you and Chris A. for the two suggestions how to replace a method.
>
> I tried both
>    inst.method = functools.partial(new_method, inst)
> and
>    inst.method = new_method.__get__(inst)
> and both work in my toy example.
> I will try it on the real code next week.
>
> Even though the functools.partial solution is easier to understand (at
> least for me), I will probably use the __get__ solution as it avoids
> the import of an extra library.
>

The two are basically equivalent. Using functools.partial emphasizes
the fact that all you're doing is "locking in" the first parameter;
using the __get__ method emphasizes the fact that functions are,
fundamentally, the same thing as methods. Choose whichever one makes
sense to you!

ChrisA


More information about the Python-list mailing list