How to replace an instance method?

Lars Liedtke lal at solute.de
Sun Sep 18 14:16:35 EDT 2022


Hey,

What has not been mentioned yet is simple delegation.

Often you want to rewrite a method, maybe have different (more or less) parameters and additionally keep the old methods for backwards compatibility. Or mark it as deprecated at a later point. So you could write the new method and change the old method to call the new method but with the parameters the new method expects. If you explain this in the docstrings as well. Then you do not need to actually replace the method.

Or you had a completely different use-case in mind, that I missed.

Cheers

Lars


Lars Liedtke
Software Entwickler

[Tel.]
[Fax]   +49 721 98993-
[E-Mail]        lal at solute.de<mailto:lal at solute.de>


solute GmbH
Zeppelinstraße 15
76185 Karlsruhe
Germany


[Logo Solute]


Marken der solute GmbH | brands of solute GmbH
[Marken]
[Advertising Partner]

Geschäftsführer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten
Webseite | www.solute.de <http://www.solute.de/>
Sitz | Registered Office: Karlsruhe
Registergericht | Register Court: Amtsgericht Mannheim
Registernummer | Register No.: HRB 110579
USt-ID | VAT ID: DE234663798



Informationen zum Datenschutz | Information about privacy policy
https://www.solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php




Am 16.09.22 um 22:55 schrieb Ralf M.:
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