2

When defining methods in a class we do have an argument for the object on which the method is invoked i.e self.

Say I have a class Foo.

class Foo:
   def m(self):
      pass

now when we have an object of Foo, say foo.

and we do something like this,

foo_m = foo.m

and then try calling foo_m with the same parameters the way would have done with foo.m. It just works.

So How does foo_m knows what should be the value of the self argument when it is not being called in foo.m() fashion ?

on printing the foo.m, the REPL shows that its a bound method to that particular object.

Is it some other function object that keeps track of the self argument and the method to be called ?

3
  • foo_m is bound to foo.m and therefor also to the fooobject, when it is called it internally uses foo as the self parameter. Oct 28, 2015 at 7:29
  • 1
    You can think of it like a functools.partial, where self is already set to the instance and you just supply the other parameters.
    – jonrsharpe
    Oct 28, 2015 at 7:50
  • Isn't foo_m just s reference to the original object? Oct 29, 2015 at 3:54

1 Answer 1

1

A bound method is just a Python object that stores self in one of its slots. Take a look at methodobject.c for the C implementation. In Python the slot is accessible via the __self__ attribute:

>>> a = [1, 2, 3].append
>>> a
<built-in method append of list object at 0x103b39588>
>>> a.__self__
[1, 2, 3]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.