在Python中重命名'_'变量 [英] Renaming the '_' variable in Python
问题描述
我最近了解了python shell中的内置变量 _
,其目的是存储最后的控制台答案.例如:
I recently learned about the builtin variable _
in the python shell, the purpose of which is to store the last console answer. For example:
>>> 4 + 7
11
>>> _
11
>>> Test = 4
>>> Test + 3
7
>>> _
7
作为TI的长期程序员,我更愿意将此变量视为 Ans
而不是 _
.(是的,我知道这只是个人喜好,但是在任何情况下都是一个有趣的问题.)
Being a longtime TI-Basic programmer, I'm far more comfortable with thinking of this variable as Ans
instead of _
. (Yes, I know it's merely personal preference, but it's an interesting question in any case.)
问题:如何设置 Ans
变量,使其值始终与 _
变量?
Question: How do I set up my Ans
variable so that its value is always the same as the _
variable?
这并不像执行 Ans = _
一样简单,如此shell日志所示:
It's not as simple as just doing Ans = _
, as this shell log shows:
>>> "test string"
'test string'
>>> _
'test string'
>>> Ans = _
>>> Ans
'test string'
>>> list('Other String')
['O', 't', 'h', 'e', 'r', ' ', 'S', 't', 'r', 'i', 'n', 'g']
>>> _
['O', 't', 'h', 'e', 'r', ' ', 'S', 't', 'r', 'i', 'n', 'g']
>>> Ans
'test string'
推荐答案
I recommend the "get used to it" option, but if you really want to fiddle with this, you can customize sys.displayhook
, the function responsible for setting _
:
import builtins
import sys
def displayhook(value):
if value is not None:
# The built-in displayhook is a bit trickier than it seems,
# so we delegate to it instead of inlining equivalent handling.
sys.__displayhook__(value)
builtins.Ans = value
sys.displayhook = displayhook
这篇关于在Python中重命名'_'变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!