Python bound methods
28 Nov 2007
In my last post I looked at registering JavaScript object methods as callbacks. When we reference a JavaScript object method we get a function object, which is not bound to the object that it is retrieved from, and I looked at various approaches that one can use to bind a method to an object instance. I thought it might be interesting to have a look at Python’s "bound methods" to see how Python facilitates passing around object method references.
>>> class MyObject:
... def __init__(self, val):
... self.val = val
... def get_val(self):
... return self.val
...
>>> obj = MyObject(8)
>>> obj.get_val()
8
In Python when we reference an object method we don’t get a function but rather a "bound method":
>>> obj.get_val
<bound method MyObject.get_val of <__main__.MyObject instance at 0x71e18>>
A bound method is one of Python’s "callable" types (others include functions and generators.) Like a function, a bound method can be called but it is bound to the object that it was retrieved from. And when it is called, it operates on that object:
>>> f = obj.get_val
>>> f()
8
If we need to, it’s possible to access a bound method’s object and function:
>>> f.im_self
<__main__.MyObject instance at 0x71e18>
>>> f.im_func
<function get_val at 0x64d30>
In JavaScript we had to bind a method to an object instance ourselves to use it as a callback. However, in Python when we reference an object method we get a callable object that is already bound.