How to replace an instance method?

Chris Angelico rosuav at gmail.com
Fri Sep 16 17:15:49 EDT 2022


On Sat, 17 Sept 2022 at 07:07, 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.
>
> My first naive idea was
>
> inst = SomeClass()
> def new_method(self, param):
>      # do something
>      return whatever
> inst.method = new_method
>
> however that doesn't work: self isn't passed as first parameter to
> the new inst.method, instead inst.method behaves like a static method.
>
> I had a closer look at the decorators classmethod and staticmethod.
> Unfortunetely I couldn't find a decorator / function "instancemethod"
> that turns a normal function into an instancemethod.
>
> The classmethod documentation contains a reference to the standard
> type hierarchie, and there is an explanation that an instancemethod
> is sort of a dynamically created wrapper around a function, which
> is accessable as __func__.
> So I modified the last line of the example above to
>
> inst.method.__func__ = new_method
>
> but got told that __func__ is read only.
>
> I found some information about methods in the Descriptor HowTo Guide,
> but it's about how it works internally and doesn't tell how to solve
> my problem (at least it doesn't tell me).
>
> Now I'm running out of ideas what to try next or what sections of the
> documentation to read next.
>
> Any ideas / pointers?
>

You don't actually want a descriptor, since the purpose of descriptor
protocol is to give you information about the instance when the
attribute (the method, in this case) was attached to the class. In
this case, you can handle it with something far far simpler:

inst.method = functools.partial(new_method, inst)

ChrisA


More information about the Python-list mailing list