首页 > 解决方案 > 在 Python 中重命名“_”变量

问题描述

我最近了解_了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'

标签: pythonalias

解决方案


我推荐“习惯它”选项,但如果你真的想摆弄这个,你可以自定义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

推荐阅读