Python references

前端 未结 5 1453
盖世英雄少女心
盖世英雄少女心 2020-11-29 10:00

Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?

<         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 10:57

    If you do y = x, y and x are the reference to the same object. But integers are immutable and when you do x + 1, the new integer is created:

    >>> x = 1
    >>> id(x)
    135720760
    >>> x += 1
    >>> id(x)
    135720748
    >>> x -= 1
    >>> id(x)
    135720760
    

    When you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.

提交回复
热议问题