|An Introduction to Python|
by Guido van Rossum and Fred L. Drake, Jr.
Paperback (6"x9"), 124 pages
RRP £12.95 ($19.95)
Sales of this book support the Python Software Foundation! Get a printed copy>>>
9.3.4 Method Objects
Usually, a method is called right after it is bound:
MyClass example, this will return the string
However, it is not necessary to call a method right away:
x.f is a method object, and can be stored away and called at a
later time. For example:
xf = x.f while True: print xf()
will continue to print ‘hello world’ until the end of time.
What exactly happens when a method is called? You may have noticed
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
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.
|ISBN 0954161769||An Introduction to Python||See the print edition|