Let's Talk About Lambda Functions!

Bengt Richter bokr at oz.net
Thu Aug 1 22:14:42 CEST 2002


On Tue, 30 Jul 2002 19:22:50 -0400, "John Roth" <johnroth at ameritech.net> wrote:

>
>"Ian Bicking" <ianb at colorstudy.com> wrote in message
>news:mailman.1028054866.6584.python-list at python.org...
>> On Tue, 2002-07-30 at 11:05, John Roth wrote:
>> > I tend to agree with you on that one, but it's a matter of style. I
>> > observe
>> > that e.g. Smalltalk style does anonymous code blocks all over the
>place.
>>
>> I've seen people argue that you can do all the same things with
>> iterators as Smalltalk does with code blocks.  And, really, it's not
>as
>> though Smalltalk has truly novel control structures -- everything
>still
>> boils down to while, for, and if.  Smalltalk does give you easy
>> callbacks, though.
>>
>> > There's no reason my proposal couldn't be extended to anonymous
>> > classes: the syntactic issues are exactly the same. The difficulty
>is
>> > in extending it to methods, as opposed to functions. The only way
>> > to distinguish a method from a function today is to observe that
>> > methods are defined at the top level of a class; a def anywhere
>> > else is a function (I think.)
>>
>> A method is just a function that is bound to a class variable.  So you
>> can do something like:
>>
>> class X:
>>     pass
>>
>> X.func = lambda self, x: x * 2
>> x = X()
>> x.func(10)
>> ==> 20
>>
>> In fact, you can even do:
>>
>> class X:
>>     func = lambda self, x: x * 2
>
>Unfortunately, that won't work. The word 'self' is not
>magic - using it doesn't convert a function to a method.
>
No, but making it a class attribute seems to do the magic
(which can also be modified with staticmethod and  classmethod).

It works on Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
However, 'self' in this example is not even used except to get the
instance bound to it and be ignored.

 >>> class X: pass
 ...
 >>> X.func = lambda self,x: x*2
 >>> x=X()
 >>> x.func(10)
 20
 >>> class X:
 ...     func = lambda self,x: x*2
 ...
 >>> x=X()
 >>> x.func(10)
 20

>On the other hand, if 'self' was the name assigned
>to the instance in the enclosing method definition, it
>would acomplish just about everything required. I suspect
>there are a few corner cases it wouldn't handle, to
>the confusion of all and sundry.
UIAM, it (self) is just a conventional parameter name to bind
the instance object implicitly passed to the method function
as a first parameter.

 >>> class X:
 ...     def __init__(ego, v): ego.v = v
 ...     func = lambda lego: '<%s with v=%s>' %(lego,lego.v)
 ...
 >>> x=X(123)
 >>> x.func()
 '<<__main__.X instance at 0x007CF780> with v=123>'

>
>Someone who knows the language in more depth
>than I do would have to comment on that.
>
>

Regards,
Bengt Richter



More information about the Python-list mailing list