##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = lambda中多行语句 = ##startInc {{{ Jiahua Huang reply-to python-cn@googlegroups.com to python-cn date Sun, Jun 21, 2009 at 23:41 }}} subject [CPyUG:90225] [[http://groups.google.com/group/python-cn/browse_thread/thread/53c618c8309f95b4|凑合解决 lambda 里的多行语句和 print]] - python-cn`CPyUG`华蟒用户组(中文Py用户组) | Google 网上论坛 == 样例 == 多说无益, {{{ >>> import sys >>> myprint = lambda i: sys.stdout.write(str(i) + '\n') >>> foo = lambda i: not not ( ... myprint(i), ... myprint(i+1), ... myprint(i+2), ... myprint(i+3), ... ) >>> foo(1) 1 2 3 4 True }}} == 用途 == 嗯,缘由是为了让 gjots 等纯 PyGtk 程序支持 Undo/Redo 操作, {{{ 0. GtkTextView 默认不支持 Undo/Redo 操作,编辑区写错了很麻烦。 1. 不想再写 UndoBuffer ,于是简单用 GtkSourceView 代替 GtkTextView, 2. 为了编辑区切换文章后能处理好 UndoStack,需要处理 .set_text() 3. 为了不派生新类和嵌套函数,希望多个动作能放在一个 lambda 里 于是就凑合了个伪多行 lambda 4. 同时希望不修改旧的 glade 文件 于是就搬出了 override }}} 过程见附件 gjots2 补丁 * [[attachment:gjots2-undo-support.patch]] == 原因 == 让 Gtk 程序的文本编辑区(GtkTextView)支持 Undo/Redo 基本上就是两个做法: * 1. 自己写 UndoBuffer 或通过其他机制,用一个 UndoStack 来记录编辑操作 * 2. 省事点就直接用 GtkSourceView 代替 GtkTextView,GtkSourceView 是 Gnome 的代码编辑控件,用法兼容 GtkTextView,但是增加了 Undo/Redo 和语法高亮等特性 所以比较起来, 我用的方法还是相对较 Kiss 的~ * 只是为了不用派生新类,直接利用 python 的动态特性修改类实例的方法 (即那个 self.textBuffer.set_text) 而 lambda 只是为了修改方法不用定义新函数~ == 改进 == {{{ Qiangning Hong reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Mon, Jun 22, 2009 at 11:19 subject [CPyUG:90259] Re: 凑合解决 lambda 里的多行语句和 print }}} {{{ foo = lambda i: (myprint(i), myprint(i+1), myprint(i+2), myprint(i+3),) and None }}} 这样foo(1)的返回值是None,更加像一个普通函数调用 :) ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]