Here is an example of probably the easiest way to add an instance method:

class Demo:
    def sqr(self, x):
        return x*x

# Function to turn into a instance method
def cube(self, x):
    return x*x*x

d = Demo()
print(d.sqr(2))

d.cube = cube.__get__(d)
print(d.cube(3))

As for when someone might want to do this kind of thing, one place is when you are running scripts in an existing framework, and you can't change the class definition but you can access an instance. Or you might want to add the method to an existing class to debug and tune it up before you go through the formalities of actually changing an existing project.

I once added a class to an running text editor so that it would highlight the current line. That was adding a class instead of a method, but the need was basically the same.

On 9/16/2022 6:35 PM, Dan Stromberg wrote:
On Fri, Sep 16, 2022 at 2:06 PM Ralf M. <ral...@t-online.de> wrote:

I would like to replace a method of an instance, but don't know how to
do it properly.


You appear to have a good answer, but...  are you sure this is a good idea?

It'll probably be confusing to future maintainers of this code, and I doubt
static analyzers will like it either.

I'm not the biggest fan of inheritance you'll ever meet, but maybe this is
a good place for it?

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to