I got some confusion with the following pygatt code example regarding a python function call. In the end: when you see a function call in python code it could well be a bound-method being called on an instance of another object. This can be achieved by passing the bound-method to a variable, and you call the variable as a function.
This seems hard for human to be aware of. For python coders, do you have to check every function call whether it is a bound-method when you read python code? As I read about bound-method is a descriptor, do you have to understand the whole descriptor concept to under a piece of python code?
Is that the right direction and is that all?
Below is the long story how it got me to ask this question.
So I asked "python use instance method as callback function - how to get a reference to the instance for the class for the method" here regarding my initial confusion with the following code snippet.
The triggering point was regarding the scan_cb
callback in pygatt library. An illustration can be:
class BGLibBackend:
def __init__(self):
self._scan_cb = None
def set_cb(self, scan_cb):
self._scan_cb = scan_cb
def service(self):
if self._scan_cb is not None:
self._scan_cb(...)
class UserApp:
def user_cb(theobj, ...):
.....when it reaches here, how to get the self that is an instance of UserAPP ?
def __init__(self):
self._bg = BGLibBackend()
self._bg.set_cb(self.user_cb):
It looked to me when the method callback user_cb()
is called, the first argument thisobj
appeared to be a reference to the caller instance, that would be an instance of BGLibBackend
. However with hints in the comments, it turned out to be an instance of UserApp
.
To this point, I wondered whether calling a normal function and a bound-method will have exactly same effect, or whether you have to know about some more rules so as to deal with them differently.
From a SO post, it looks I'll need to understand the descriptor concept behind a function. Probably that will solve my concern. But I'm also wondering whether there is more than a descriptor, or whether descriptor is a wrong direction to understanding this.
Thanks.