Strange Python behavior from inappropriate usage of 'is not' comparison?

后端 未结 5 805
南方客
南方客 2021-01-22 15:12

I (incorrectly?) used \'is not\' in a comparison and found this curious behavior:

>>> a = 256
>>> b = int(\'256\')
>>> c = 300
>>         


        
5条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 15:53

    For small numbers, Python is reusing the object instances, but for larger numbers, it creates new instances for them.

    See this:

    >>> a=256
    >>> b=int('256')
    >>> c=300       
    >>> d=int('300')
    
    >>> id(a)
    158013588
    >>> id(b)
    158013588
    >>> id(c)
    158151472
    >>> id(d)
    158151436
    

    which is exactly why a is b, but c isn't d.

提交回复
热议问题