在Python / IPython解释器中为单个下划线_赋值
I created this function in Python 2.7 with ipython
:
我使用ipython在Python 2.7中创建了这个函数:
def _(v):
return v
later if I call _(somevalue)
, I get _ = somevalue
.
后来如果我调用_(somevalue),我得到_ = somevalue。
in[3]: _(3)
out[3]: 3
in[4]: print _
out[4]: 3
The function has disappeared! If I call _(4)
I get:
功能消失了!如果我打电话给_(4)我得到:
TypeError: 'int' object is not callable`
Why? What's wrong with this function?
为什么?这个功能有什么问题?
3 个解决方案
#1
101
The Python interpreter assigns the last expression value to _
.
Python解释器将最后一个表达式值赋给_。
This behaviour is limited to the REPL interpreter only, and is intended to assist in interactive coding sessions:
此行为仅限于REPL解释器,旨在帮助进行交互式编码会话:
>>> import math
>>> math.pow(3.0, 5)
243.0
>>> result = _
>>> result
243.0
The standard Python interpreter goes to some length to not trample on user-defined values though; if you yourself assign something else to _
then the interpreter will not overwrite that (technically speaking, the _
variable is a __builtin__
attribute, your own assignments are 'regular' globals). You are not using the standard Python interpreter though; you are using IPython, and that interpreter is not that careful.
标准的Python解释器有一定篇幅,但不会践踏用户定义的值;如果你自己为_分配其他东西,那么解释器就不会覆盖它(从技术上讲,_变量是__builtin__属性,你自己的赋值是'常规'全局变量)。你没有使用标准的Python解释器;你正在使用IPython,那个解释器并不那么谨慎。
IPython documents this behaviour explicitly:
IPython明确记录了这种行为:
The following GLOBAL variables always exist (so don’t overwrite them!):
以下GLOBAL变量始终存在(因此不要覆盖它们!):
[_]
(a single underscore) : stores previous output, like Python’s default interpreter.- [_](单个下划线):存储以前的输出,如Python的默认解释器。
[...]
[...]
Outside of the Python interpreter, _
is by convention used as the name of the translatable text function (see the gettext
module; external tools look for that function to extract translatable strings).
在Python解释器之外,_按惯例用作可翻译文本函数的名称(请参阅gettext模块;外部工具查找该函数以提取可翻译的字符串)。
In loops, using _
as an assignment target tells readers of your code that you are going to ignore that value; e.g. [random.random() for _ in range(5)]
to generate a list of 5 random float values.
在循环中,使用_作为赋值目标告诉读者您的代码将忽略该值;例如[random_random()for _ in range(5)]生成5个随机浮点值的列表。
更多相关文章
- Python中int()函数的用法
- python 函数式编程
- Python内置函数之匿名(lambda)函数
- python函数的属性
- python学习笔记10(函数一): 函数使用、调用、返回值
- Linux下共享内存相关函数
- Linux回调函数的应用---已经验证
- c中变参函数的理解和编写(hello world引发的思考)
- 浅谈Oracle函数返回Table集合