Python下划线作为函数参数
我有一个特定于 python 的问题。单个下划线_
作为参数意味着什么? 我有一个调用 hexdump(_)
的函数。 _ 从未定义过,所以我猜它有一些特殊的价值,我找不到参考资料告诉我它在网上的含义。如果你能告诉我,我会很高兴。
I have a python specific question. What does a single underscore _
as a parameter means?
I have a function calling hexdump(_)
. The _ was never defined, so I guess it has some special value, I could not find a reference telling me what it means on the net. I would be happy if you could tell me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
据我所知,情况似乎是这样的:
_
用于指示输入变量是一个一次性变量/参数,因此可能是必需的或预期的,但不会在其后面的代码中使用。例如:(
归功于 这篇文章)
我遇到的具体示例是这样的:
From what I've been able to figure out, it seems like this is the case:
_
is used to indicate that the input variable is a throwaway variable/parameter and thus might be required or expected, but will not be used in the code following it.For example:
(Credit to this post)
The specific example I came across was this:
在 Python shell 中,下划线 (
_
) 表示 shell 中最后一次计算表达式的结果:还有
_2
、_3
等在 IPython 中,但在原始 Python 解释器中没有。据我所知,它在Python源代码中没有特殊含义,所以我猜如果它运行没有错误的话,它是在代码中的某个地方定义的。In Python shells, the underscore (
_
) means the result of the last evaluated expression in the shell:There's also
_2
,_3
and so on in IPython but not in the original Python interpreter. It has no special meaning in Python source code as far as I know, so I guess it is defined somewhere in your code if it runs without errors.下划线被认为是“不关心”变量,此外,如果未使用它,像 PyCharm 这样的 IDE 不会给出警告,
因此在函数中
IDE 会在 a、b 和 c(未使用的参数)下划线,但不会
在下划线处 添加下划线你使用它并且不省略参数?
->当您从某个类继承并想要重写您不想使用某些参数的函数时,
其他常见用途是指示您在迭代(或其他解包)时不想使用元组的一部分) - 这减少了混乱
,我在任何 python PEP 中都找不到它,但 pylint 即使在 常见问题解答
underscore is considered a 'don't care' variable, furthermore IDEs like PyCharm will not give a warning for it if it is unused
so in a function
the IDE will underline a,b and c (unused parameter) but not the underscore
why would you use it and not omit the parameter?
->when you inherit from some class and want to override a function where you don't want to use some parameter
other common use is to indicate you don't want to use a part of a tuple when you iterate (or other unpacking) - this reduces clutter
I cant find it in any python PEP, but pylint has it even in the FAQ
它在您编写的代码中没有特殊的价值。它存储您在交互式解释器中计算的最后一个表达式的结果,并且为了方便使用
It doesn't have a special value in the code you write. It stores the result of the last expression you evaluated in your interactive interpreter and is used for convenience