在Python中重命名'_'变量

时间:2018-05-07 16:03:14

标签: python alias

我最近在python shell中了解了内置变量_,其目的是存储最后一个控制台答案。例如:

>>> 4 + 7
11
>>> _
11
>>> Test = 4
>>> Test + 3
7
>>> _
7

作为一名长期的TI-Basic程序员,我更愿意将此变量视为Ans而不是_。 (是的,我知道这只是个人偏好,但无论如何这都是一个有趣的问题。)

问题:如何设置我的Ans变量,使其值始终_变量相同?

这并不像执行Ans = _那么简单,因为这个shell日志显示:

>>> "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 个答案:

答案 0 :(得分:9)

我建议"习惯它"选项,但如果你真的想摆弄这个,你可以自定义sys.displayhook,负责设置_的功能:

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
相关问题