【问题标题】:What's the meaning of '_' in python?python中'_'的含义是什么?
【发布时间】:2010-10-19 10:05:45
【问题描述】:

在阅读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")

我知道它将描述设置为“整数”,但不理解语法:description = _("Integer")
有人可以帮忙吗?

【问题讨论】:

标签: python django syntax


【解决方案1】:

请阅读国际化 (i18n)

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

_ 是用于将字符串翻译成另一种语言的函数的常用名称。

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

另外,请阅读关于 SO 的所有这些相关问题:

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

【讨论】:

    【解决方案2】:

    不是您的案例的答案,而是更笼统的“python中'_'的含义是什么?”:

    交互模式中,_ 将返回最后一个未分配给变量的结果

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

    不确定,但似乎每个未分配给变量的表达式实际上都分配给了_

    【讨论】:

    • python 程序中似乎还有另一种用法'_'。如:I_need,_,I_need_2 = ('a','b','c');在这种情况下,您不需要关心元组中的第二个值,因此可以节省您为这些无用值考虑变量名称的时间,从而使代码更易于阅读。
    • @Beyonder:没错,但在这种情况下,它就像任何其他变量一样,只是使用最容易忘记的名称_ 说“我是一个一次性变量”。
    • 它是 Matlab 中“ans”的等价物吗?
    • @David 互动,是的。
    【解决方案3】:

    这用于gettext函数,如here所述

    对 django 的 Utf-8 支持很好,因此 django 将其作为 unicodetext 处理,如 here 所述

    【讨论】:

      【解决方案4】:

      _ 表示屏幕上的最后一个有效输出。默认情况下,系统将输出的副本存储到此 _ 变量。它不适用于使用 print 函数打印的字符串,但我存储存储在变量中的字符串。

      enter image description here

      【讨论】:

        猜你喜欢
        • 2021-05-13
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 2020-08-23
        • 2015-04-09
        • 2019-04-17
        • 2011-06-01
        • 1970-01-01
        相关资源
        最近更新 更多