search

Home  >  Q&A  >  body text

c - 为什么python中值相等的两个变量会指向同一个内存地址?

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

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

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

天蓬老师天蓬老师2876 days ago569

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 10:36:11

    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

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:36:11

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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:36:11

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

    reply
    0
  • Cancelreply