Py和"_"

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

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

i18N用

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

能不能说得不要那么笼统,

_() 函数调用是国际化用的,
会将给出参数的翻译文本,
_("Hello") 会返回像是 "你好",
Widget.set_text(_("Hello")) 会是
Widget.set_text("你好")

yuting cui <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Sat, Jul 19, 2008 at 21:14

嗯,为了和gnu的gettext常用语法兼容

import gettext
_ = gettext.gettext

免冲突

Iceberg <[email protected]>
reply-to        [email protected]
to      python-cn`CPyUG`华蟒用户组 <[email protected]>
date    Sun, Jul 20, 2008 at 10:54

 _ , ext = os.path.splitext('/tmp/something.txt')

Iceberg

理性用

Leo Jay <[email protected]>
reply-to        [email protected]
to      [email protected]
date    Sun, Jul 20, 2008 at 11:00

如果是我,我不会这样用。我会写:

ext = os.path.splitext('/tmp/something.txt')[1]

一定要写一个变量的时候,我会起一个明显一些的名字。

dummy, ext = os.path.splitext('/tmp/something.txt')

交互解

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中有类似的用法。

补充

DIrk


反馈

创建 by -- ZoomQuiet [2008-07-22 00:01:19]

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