Renaming the '_' variable in Python

北战南征 提交于 2021-02-08 07:51:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!