python - 在 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'
解决方案
我推荐“习惯它”选项,但如果你真的想摆弄这个,你可以自定义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
推荐阅读
- css - 如何使用 print-CSS 拆分长 HTML 表格,以便第一页表格中的拆分为页面底部的 div 留出空间?
- pyinstaller - 在EXE中使用PyInstaller打包数据文件
- c++ - 通过 lambda 部分专门化类模板
- c# - 如何正确反序列化 Json DateTimeOffset?
- ruby - 如何将字符串拆分为 n 个子字符串?
- php - 显示错误:上传路径似乎无效
- c# - 有没有办法禁用所有 WPF 应用程序的缩放,即使 Windows 在每个监视器或系统范围内都有一定的缩放比例?
- cuda - Cuda - nvcc - 没有可在设备上执行的内核映像。问题是什么?
- html - 在 Chrome 中编辑 CSS 规则时不要突出显示 HTML 区域
- mysql - 如何在执行 SQL 转储时替换某些列的值