faqts : Computers : Programming : Languages : Python : Language and Syntax : Classes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 14 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

If an instance of an object passes a reference to one of its methods, how does python keep track of the instance?

May 10th, 2000 03:26
unknown unknown, Quinn Dunkan, Stefan Franke


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.

A "bound method" basically keeps a pair of references - to the method
and the instance:

>>> class C: pass
>>> class C:
...     def a(): pass
>>> C.a
<unbound method C.a>
>>> C().a
<method C.a of C instance at 1a20e10>