c - 为什么python中值相等的两个变量会指向同一个内存地址?
天蓬老师
天蓬老师 2017-04-18 10:34:11
0
3
567

http://www.cnblogs.com/lolein... 下面是这个文章里面所演示的代码,

>>> a=1
>>> b=1
>>> id(a)
40650152
>>> id(b)
40650152
>>> a=2
>>> id(a)
40650140

我有点费解的就是,按道理a和b完全就不是同一个变量,那么理论上他们无论值是什么,都应该是放在两个不同的内存空间啊,为什么他们相等的时候就放在了同一个内存空间呢?难道是python的运行时环境会自动判断他们的值,如果相同就放到同一个内存空间,为的是节省内存占用吗?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
迷茫

Python has a small integer pool when implementing int. For efficiency, Python first creates these integers internally, and then reuses this part of the integers to create an int with a value of 1. In fact, it takes 1 directly from this pool.
Generally -5 to 257. Get 1,000, 500 or something and see. That won't be the case anymore.
Look at this:
python integer object implementation

黄舟

Constant pool is used for performance optimization. And this is not unique to python, many other languages ​​use similar techniques.

左手右手慢动作

https://github.com/python/cpy...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template