How to replace an instance method?

Ralf M. Ralf_M at t-online.de
Fri Sep 16 16:55:52 EDT 2022


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?

Ralf M.


More information about the Python-list mailing list