Retrieving the list of references to an object in Python

后端 未结 7 1217
栀梦
栀梦 2020-12-04 01:29

All:

a = 1
b = a
c = b

Now I want to get a list of object 1 tagged, which is [a, b, c]. How could I do this?

相关标签:
7条回答
  • 2020-12-04 02:28

    I'd like to clarify some misinformation here. This doesn't really have anything to do with the fact that "ints are immutable". When you write a = 2 you are assigning a and a alone to something different -- it has no effect on b and c.

    If you were to modify a property of a however, then it would effect b and c. Hopefully this example better illustrates what I'm talking about:

    >>> a = b = c = [1]  # assign everyone to the same object
    >>> a, b, c
    ([1], [1], [1])
    >>> a[0] = 2         # modify a member of a
    >>> a, b, c
    ([2], [2], [2])      # everyone gets updated because they all refer to the same object
    >>> a = [3]          # assign a to a new object
    >>> a, b, c
    ([3], [2], [2])      # b and c are not affected
    
    0 讨论(0)
提交回复
热议问题