Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use callback functions with object/method pair

I have a simple method which accepts a function to call this back later:

def SimpleFunc(parm1):
    print(parm1)

class CallMe:
    def __init__(self, func):
        self.func = func

    def Call(self, parm):
        self.func(parm)

caller = CallMe(SimpleFunc)
caller.Call("Hallo")

That works fine!

But I want to use a class method and want to call the method on a defined object as callback:

class WithClassMethod:
    def __init__( self, val ):
        self.val = val 

    def Func(self, parm):
        print( "WithClass: ", self.val, parm )


obj = WithClassMethod(1)
caller = CallMe( ??? )
caller.Call("Next")

How can I bind an object/method pair to a callable object?

Attention: The code from CallMe is not under my control. It comes from a webserver which needs a handler function.

like image 484
Klaus Avatar asked Feb 06 '23 06:02

Klaus


1 Answers

You could simply pass the method object to the class:

called = CallMe(obj.Func)

To expand a bit, instance methods are really just the original class function:

>>> obj.Func.__func__
<function __main__.WithClassMethod.Func>

which, during access on an instance (obj.Func) are transformed via a descriptor (__get__) that attaches self (the instance) to them:

>>> obj.Func.__self__
<__main__.WithClassMethod at 0x7fbe740ce588>

so you can pretty much do anything you want with methods as with functions.

like image 174
Dimitris Fasarakis Hilliard Avatar answered Feb 08 '23 15:02

Dimitris Fasarakis Hilliard