I’m using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct ‘self’ argument, so I’m wondering how to turn a method into a function that knows what ‘self’ it belongs to.
There are a couple of ways that I can think of to do this, including using a lambda and a closure. I’ve included some examples of this below, but I’m wondering if there is a standard mechanism for achieving the same effect.
class A(object): def hello(self, salutation): print('%s, my name is %s' % (salutation, str(self))) def bind_hello1(self): return lambda x: self.hello(x) def bind_hello2(self): def hello2(*args): self.hello(*args) return hello2 >>> a1, a2 = A(), A() >>> a1.hello('Greetings'); a2.hello('Greetings') Greetings, my name is <__main__.A object at 0x71570> Greetings, my name is <__main__.A object at 0x71590> >>> f1, f2 = a1.bind_hello1(), a2.bind_hello1() >>> f1('Salutations'); f2('Salutations') Salutations, my name is <__main__.A object at 0x71570> Salutations, my name is <__main__.A object at 0x71590> >>> f1, f2 = a1.bind_hello2(), a2.bind_hello2() >>> f1('Aloha'); f2('Aloha') Aloha, my name is <__main__.A object at 0x71570> Aloha, my name is <__main__.A object at 0x71590>
Will passing in the method bound to a instance work? If so, you don’t have to do anything special.