Python:_("str")是什么意思?

9
我在Django源代码中看到了这个:

我在Django源代码中看到了这个:

description = _("Comma-separated integers")
description = _("Date (without time)")

它是做什么的?我尝试在Python 3.1.3中使用它,但失败了。
>>> foo = _("bar")
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    foo = _("bar")
NameError: name '_' is not defined

在2.4.4中也没有运气:

>>> foo = _("bar")

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    foo = _("bar")
NameError: name '_' is not defined

这里发生了什么?


3
这通常用于为GNU gettext标记可翻译的字符串。 - Sven Marnach
3个回答

19

_是一个普通的变量名,和其他变量名一样。语法_(x)是用来调用函数_并传递参数x的。在这个例子中,它被用作ugettext的别名,ugettext是Django定义的用于字符串翻译的函数。根据文档

指定翻译字符串:在Python代码中

标准翻译

使用函数ugettext()指定翻译字符串。按照惯例将其导入为较短的别名_以节省时间。

要在您自己的代码中使用_,您可以使用如下导入语句:

from django.utils.translation import ugettext as _

类似于这里:http://code.djangoproject.com/browser/django/trunk/django/core/validators.py#L5 - TryPyPy

1

_符号在Python中只是一个变量名,而在这种情况下,它似乎是指一个接受字符串作为参数的函数或其他“可调用对象”。例如:

 def myfun(strng):
     return "input = " +  strng

 _ = myfun

 description = _("Comma-separated integers")

0

需要注意的是,如果你想让``makemessages``检测到字符串,就不能随意选择任何别名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接