Python: different objects get the same id

前端 未结 2 660
暗喜
暗喜 2021-01-20 16:41

Looking at the following IPython (Python 3.7) session:

In [1]: id(\'hello\')                                                     
Out[1]: 140300950123104

In         


        
2条回答
  •  攒了一身酷
    2021-01-20 17:27

    This is an interesting question, but it's well explained in wtfpython.

    When a and b are set to "hello" in the same line, the Python interpreter creates a new object, then references the second variable at the same time. If you do it on separate lines, it doesn't "know" that there's already hello as an object (because "hello" is not implicitly interned as per the facts mentioned above). It's a compiler optimization and specifically applies to the interactive environment.

    One thing that differs is that in IPython, things might be a bit different from direct Python REPL, so this explains the difference in id in your first two inputs.

提交回复
热议问题