Python integer caching

后端 未结 2 1019
攒了一身酷
攒了一身酷 2020-12-03 23:02

In the following python script, why the second assert goes through (i.e., when adding 0 to 257 and stores the result in y, then x and y become different objects)? Thanks!

2条回答
  •  萌比男神i
    2020-12-03 23:47

    integers are non mutable so any operation to change them results in a new memory location

    >>> a =9876
    >>> id(a)
    38478552
    >>> a+=1
    >>> id(a)
    38478576
    >>> a+=0
    >>> id(a)
    38478528
    

    is is checking the actual memory location of the object ... and should basically never be used to check for value equality (although it may arbitrarily work on some small subset of cases)

提交回复
热议问题