python def 下划线_在Python / IPython解释器中为单个下划线_赋值

本文探讨了在使用Python 2.7的IPython环境中,定义函数`_`作为变量名可能导致的问题。当你尝试调用这个未赋实际函数的变量时,会得到TypeError。这是因为Python交互式解释器会将上一条表达式的值赋予`_`,而非作为一个函数。这仅限于REPL环境,标准解释器会保护用户自定义变量。IPython的这种特性可能带来的误解和意外情况需注意。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I created this function in Python 2.7 with ipython:

def _(v):

return v

later if I call _(somevalue), I get _ = somevalue.

in[3]: _(3)

out[3]: 3

in[4]: print _

out[4]: 3

The function has disappeared! If I call _(4) I get:

TypeError: 'int' object is not callable`

Why? What's wrong with this function?

解决方案

The Python interpreter assigns the last expression value to _.

This behaviour is limited to the REPL interpreter only, and is intended to assist in interactive coding sessions:

>>> 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.

The following GLOBAL variables always exist (so don’t overwrite them!):

[_] (a single underscore) : stores previous output, like Python’s default interpreter.

[...]

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).

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值