Python中'_'的含义是什么?

22 投票
4 回答
10577 浏览
提问于 2025-04-16 05:44

在阅读Django的源代码时,我发现了一些语句:

class Field(object):  
    """Base class for all field types"""  
    __metaclass__ = LegacyConnection  

    # Generic field type description, usually overriden by subclasses
    def _description(self):
        return _(u'Field of type: %(field_type)s') % {
            'field_type': self.__class__.__name__
        }    
    description = property(_description) 

class AutoField(Field):
    description = _("Integer")

我知道它把描述设置为'Integer',但是不太明白这个语法:description = _("Integer")
有人能帮我解释一下吗?

4 个回答

6

这是用来解释gettext函数的,详细内容可以在这里找到。

Django对Utf-8的支持很好,所以Django会把它当作Unicode文本来处理,具体信息可以在这里查看。

13

这不是针对你问题的答案,而是更一般的“在Python中,'_'是什么意思?”

交互模式下,_会返回最后一个没有被赋值给变量的结果。

>>> 1 # _ = 1
1
>>> _ # _ = _
1
>>> a = 2
>>> _
1
>>> a # _ = a
2
>>> _ # _ = _
2
>>> list((3,)) # _ = list((3,))
[3]
>>> _ # _ = _
[3]

我不太确定,但似乎每个没有被赋值给变量的表达式实际上都是赋值给_的。

27

请了解一下国际化(i18n)

http://docs.djangoproject.com/en/dev/topics/i18n/

_ 是一个常用的函数名称,用来把字符串翻译成其他语言。

http://docs.djangoproject.com/en/dev/topics/i18n/translation/#standard-translation

另外,也可以看看这些相关的问题:

https://stackoverflow.com/search?q=%5Bdjango%5D+i18n

撰写回答