passing methods/functions

Quinn Dunkan quinn at hedono.ugcs.caltech.edu
Sun May 7 14:07:47 EDT 2000


On Sun, 07 May 2000 07:29:48 GMT, Courageous <jkraska1 at san.rr.com> wrote:
>
>Passing around "pointers to functions" is something I intrinsically
>understand, but if an instance of an object passes a reference to
>one of its methods, how does python keep track of the instance?
>
>When I first tried this, I presumed that I'd be delivering the
>self argument upon invocation the hard way. This appears to not
>be the case. Very cool. But how's this work?

A method is a wrapper around a normal python function.  It has the attrs
im_func, im_class, and im_self.  im_func is a normal function object, and 
im_class is the method's class.  When you pull a method from an instance:
instance.method.im_self, the instance is magically stored in im_self.  If you
look at the im_self of a class: Class.method.im_self, it will be None (which
is what makes an unbound method an unbound method).

When you call a bound method wrapper, it calls its im_func with im_self
prepended to the argument list.

So that's where python is hiding 'self'.  You can think of a method as a
little closure.



More information about the Python-list mailing list