Wednesday, 23 January 2008

HOWTO: lambda in Python

By popular demand, a few features commonly found in functional programming languages like Lisp have been added to Python. With the lambda keyword, small anonymous functions can be created. Here's a function that returns the sum of its two arguments: "lambda a, b: a+b". Lambda forms can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda forms can reference variables from the containing scope:

>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43


lambda很灵活,可以用在任何需要函数的地方:

>>>def f(x):
… return x*2

>>> f(2)
4

定义一个函数f(x),f(x)=x*2. 用lambda来表达就是:

>>> f=lambda x: x*2
>>> f(2)
4

这个函数没有函数名,lambda的结果被赋值给变量f调用。

############################################
对于Tkinter,
可以直接用lambda直接设置一些简单callback:
b = Button(master, text="Delete",command = lambda listbox=listbox: listbox.delete(ANCHOR))
在这种情况下,需要设定返回值(listbox=),然后才是lambda的参数(listbox).

这种简写方式等效于:(如下code是在一个class内的代码)

self.b = Button(master, text="Delete",command = self.toremove)
##self.b = Button(master, text="Delete",command = lambda llb=lb: lb.delete(ANCHOR))
def toremove(self):
self.listbox.delete(ANCHOR)

Powered by ScribeFire.

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter