简体   繁体   English

下划线在Python中代表什么?

[英]What does the underscore represent in Python?

I am kind of new to Python, so I am trying to read over existing code. 我是Python的新手,所以我试图阅读现有的代码。 I am a little confused on the syntax of this though. 我对这个语法有点困惑。

For example: 例如:

rlist, _, _ = select.select(sockets, [], [])

I understand that select.select() takes 3 lists (and I assume [] just means empty list), but is the _ used to denote a placeholder of some sort? 我知道select.select()需要3个列表(我假设[]只是表示空列表),但是_用于表示某种占位符吗?

It's just the name of a variable! 它只是变量的名称! Usually people use _ for variables that are temporary or insignificant. 通常人们使用_作为临时或无关紧要的变量。

As other people have stated, _ is a common alias for gettext, a translation library. 正如其他人所说, _是gettext(翻译库)的常见别名。 You can identify when it's being used as gettext if you see it called as a function, eg. 如果您将其视为函数,则可以确定何时将其用作gettext,例如。 _('Hello, world!') . _('Hello, world!')

Protip: In the python console it can be used to retrieve the result of the last statement. Protip:在python控制台中,它可以用来检索最后一个语句的结果。

>>> 3 + 4
7
>>> a = _
>>> print a
7

It's just an anonymous variable, and has no special meaning to python. 它只是一个匿名变量,对python没有特殊意义。 Compare it with using i as a loop counter. 将它与使用i作为循环计数器进行比较。

You generally use it to document that the surrounding code is going to ignore the value of that variable. 您通常使用它来记录周围的代码将忽略该变量的值。

In the python interactive console, the result of the last expression is assigned to _ , but that does not carry through in python programs. 在python交互式控制台中,最后一个表达式的结果被赋值给_ ,但这不会在python程序中进行。

Despite what the other answers say, _ does have a special meaning in Python. 尽管其他答案都说, _在Python中确实有特殊含义。 It's the last result printed at the interactive prompt. 这是在交互式提示下打印的最后一个结果。

>>> 2+2
4
>>> _+2
6

(Of course if there is no interactive prompt, eg, because you're running a Python script from the shell, then it doesn't have a special meaning.) (当然,如果没有交互式提示,例如,因为您从shell运行Python脚本,那么它没有特殊含义。)

It represents an anonymous variable . 它代表一个匿名变量 It's used because the variable is required but the value can be ignored. 之所以使用它是因为变量是必需的,但可以忽略该值。

Generally, you name a variable with a single underscore when you never need to refer to the variable again. 通常,当您永远不需要再次引用变量时,可以使用单个下划线命名变量。 For example, something like this: 例如,像这样:

for _ in range(10):
    print "hello"

This just prints "hello" 10 times, and we never need to refer to the loop control variable ( _ in this case). 这只是打印“hello”10次,我们永远不需要引用循环控制变量(在这种情况下为_ )。

In your example, select.select(sockets, [], []) returns a tuple (or list or set) from which you seemingly only need the first item, hence you the use of the underscores. 在您的示例中, select.select(sockets, [], [])返回一个元组(或列表或集合),您似乎只需要第一个项目,因此您使用下划线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM