Let's Talk About Lambda Functions!

Greg Ewing see_reply_address at something.invalid
Mon Aug 5 06:28:58 CEST 2002


John Roth wrote:

> 
> In other words,
> 
> class foo:
>     bar = (
>         def (x, y):
>             print x
>             print y
>         )
> 
> makes the anonymous function a method because it's
> bound to a name in the class namespace?


Closer, but the distinction is actually made even
later than that. As long as it's sitting in the class
namespace, it's still just an ordinary function.
You can see this by looking at foo.__dict__["bar"].
You'll see that it's just a plain function taking
two arguments. [See footnote.]

If you have an instance f of class foo, then when
the expression

    f.bar

is evaluated, at *that* point a "bound method object"
is created, which is a callable object containing a
reference to f and a reference to the original
function (which is still sitting unaltered in
foo.__dict__).

So, in one sense, being in a class namespace means
that a function is a method. But (the way Python is
currently implemented) there's no physical difference
until you come to *use* it as a method!

Confused enough yet?-)

------------
Footnote: If you just evaluate foo.bar, another piece
of magic kicks in and returns an "unbound method object"
instead. You have to look directly in foo.__dict__ to
find out what's *really* there.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list