class objects, method objects, function objects

7stud bbxx789_05ss at yahoo.com
Mon Mar 19 00:44:50 EDT 2007


Oops, here is that last sentence in context(section 9.3.4):
------------
What exactly happens when a method is called? You may have noticed
that x.f() was called without an argument above, even though the
function definition for f specified an argument. What happened to the
argument? Surely Python raises an exception when a function that
requires an argument is called without any -- even if the argument
isn't actually used...

Actually, you may have guessed the answer: the special thing about
methods is that the object is passed as the first argument of the
function. In our example, the call x.f() is exactly equivalent to
MyClass.f(x). In general, calling a method with a list of n arguments
is equivalent to calling the corresponding function with an argument
list that is created by inserting the method's object before the first
argument.

If you still don't understand how methods work, a look at the
implementation can perhaps clarify matters. When an instance attribute
is referenced that isn't a data attribute, its class is searched. If
the name denotes a valid class attribute that is a function object, a
method object is created by packing (pointers to) the instance object
and the function object just found together in an abstract object:
this is the method object. When the method object is called with an
argument list, it is unpacked again, a new argument list is
constructed from the instance object and the original argument list,
and the function object is called with this new argument list.
------------




More information about the Python-list mailing list