How to create the int 1 at two different memory locations?

后端 未结 3 748
不思量自难忘°
不思量自难忘° 2020-12-10 19:47

I want to show someone how using is instead of == to compare integers can fail. I thought this would work, but it didn\'t:

>>         


        
3条回答
  •  心在旅途
    2020-12-10 20:25

    What you observe is expected:

    >>> x=256
    >>> y=256
    >>> x is y
    True
    >>> x=257
    >>> y=257
    >>> x is y
    False
    >>> x=-5
    >>> y=-5
    >>> x is y
    True
    >>> x=-6
    >>> y=-6
    >>> x is y
    False
    

    Quoting from Plain Integer Objects:

    The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

提交回复
热议问题