6

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.

3
  • just caller = CallMe(obj.Func) if I'm not misunderstanding things? Commented Jan 23, 2017 at 10:54
  • @JimFasarakis-Hilliard: Ubs. I am new to python and come from c++ so I search for more difficult solutions :-) make it an answer so I can accept. Thanks! Commented Jan 23, 2017 at 11:05
  • Done, I added a bit more information to it too if interested. Commented Jan 23, 2017 at 11:13

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see. Coming from a JavaScript background, I expected self to be bound on call, not on get. That's very interesting :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.