is is not what it is!/出人意料的is! 单行赋值,交互式环境执行的版本问题
Closed this issue · 0 comments
BruceLee569 commented
文中说到当 a 和 b 在同一行中被设置为 257 时, Python 解释器会创建一个新对象, 然后同时引用第二个变量. 如果你在不同的行上进行, 它就不会 "知道" 已经存在一个 257 对象了.并且这是特别为交互式环境做的编译器优化,直接执行文件不会有此现象发生。
但是经过在我电脑测试后发现:
python 3.7.3的ipython交互式环境中:
同一行的代码a = 257; b = 257
和a, b = 257, 257
执行a is b
的结果:两者均为False
但是文件执行结果:前者False,后者为True
python 3.6.8的ipython交互式环境中:
同一行的代码a = 257; b = 257
和a, b = 257, 257
执行a is b
的结果:前者为False,后者为True
但是文件执行结果:两者均为True
详细结果如下:
python版本3.7.3
ipython交互式环境运行:
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a = 257; b = 257
In [2]: a is b
Out[2]: False
In [3]: a, b = 257, 257
In [4]: a is b
Out[4]: False
控制台命令
python 文件名
运行:
a, b = 257, 257
print(a is b) # False
a = 257; b = 257
print(a is b) # True
python版本3.6.8
ipython交互式环境运行:
Python 3.6.8 (default, May 2 2019, 20:40:44)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a = 257; b = 257
In [2]: a is b
Out[2]: False
In [3]: a, b = 257, 257
In [4]: a is b
Out[4]: True
控制台命令
python 文件名
运行:
a, b = 257, 257
print(a is b) # True
a = 257; b = 257
print(a is b) # True