Differences between revisions 1 and 2
Revision 1 as of 2008-07-22 00:01:19
Size: 1474
Editor: ZoomQuiet
Comment:
Revision 2 as of 2008-07-22 00:03:15
Size: 1702
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 51: Line 51:
== 补充 ==
 * 补充一下,发生给_赋值的情况仅限于先前的返回值不是None.
 * 而且,这应该只是在Python命令交互模式才有效果,在脚本中为了避免隐藏bug,不存在这种情况。

TableOfContents

Include(ZPyUGnav)

Py和"_"

    Boern <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Sat, Jul 19, 2008 at 15:12
subject [CPyUG:59688] python 中单独一个 下划线 代表什么意思?

在一些开源项目中,经常见到方法参数或者返回值 用一个 "_ " 来表示,不知道代表什么意

正解

DIrk <[email protected]>
reply-to        [email protected]
to      python-cn`CPyUG`华蟒用户组 <[email protected]>
date    Mon, Jul 21, 2008 at 08:49

以下是正确解释:

在Python中,_ 符号一般代表着最近一条应该有返回值而没有被赋给某个变量的语句的执行结果,比如以下语句:

abc = 'xxx'
cde = 'yyy'
abc + cde

这里的最后一条, abc + cde, 没有明确赋给哪个变量,Python 会自动将其赋给 _ 这个特殊符号。

如果你改写成:

abc = 'xxx'
cde = 'yyy'
fgh = abc + cde

就不会发生 _ = abc + cde 这样的赋值情况了。

大家可以试试。

其实,记得在Perl中有类似的用法。

补充

  • 补充一下,发生给_赋值的情况仅限于先前的返回值不是None.
  • 而且,这应该只是在Python命令交互模式才有效果,在脚本中为了避免隐藏bug,不存在这种情况。

DIrk


反馈

创建 by -- ZoomQuiet [DateTime(2008-07-22T00:01:19Z)]

PageComment2

[:/PageCommentData:PageCommentData]

MiscItems/2008-07-22 (last edited 2009-12-25 07:16:13 by localhost)