问题
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
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.)
Question: How do I set up my Ans
variable so that its value is always the same as the _
variable?
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'
回答1:
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
来源:https://stackoverflow.com/questions/50218274/renaming-the-variable-in-python