【发布时间】:2012-02-03 14:29:51
【问题描述】:
我想指出一个什么都不做的函数:
def identity(*args)
return args
我的用例是这样的
try:
gettext.find(...)
...
_ = gettext.gettext
else:
_ = identity
当然,我可以使用上面定义的identity,但是内置的肯定会运行得更快(并且避免我自己引入的错误)。
显然,map 和 filter 使用 None 作为标识,但这是特定于它们的实现的。
>>> _=None
>>> _("hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
【问题讨论】:
-
map and filter use None for the identity是什么意思? -
@MattFenwick:
map(None, [1, 2, 3]) -
查看返回值。您的 args 变量将是(在这种情况下)一个值的序列,因此要么在声明中省略星号,要么在返回之前将其解包。
-
@GregHewgill:遗憾的是,这在 Python 3.x 中不起作用。
-
@GregHewgill 我的错。我在谷歌搜索后从文档中获取了它。但是 Python2.x 文档总是排在第一位的……
标签: python python-3.x python-2.7