Python list append causes strange result

前端 未结 5 1293
执念已碎
执念已碎 2021-01-29 00:55

I have really strange problem. Here is the sample code:

class SomeClass(object):
    a = []
    b = []
    def __init__(self, *args, **kwargs):
        self.a =          


        
5条回答
  •  北海茫月
    2021-01-29 01:40

    You are assigning the same list to self.b, not a copy.

    If you wanted self.b to refer to a copy of the list, create one using either list() or a full slice:

    self.b = self.a[:]
    

    or

    self.b = list(self.a)
    

    You can test this easily from the interactive interpreter:

    >>> a = b = []  # two references to the same list
    >>> a
    []
    >>> a is b
    True
    >>> a.append(42)
    >>> b
    [42]
    >>> b = a[:]  # create a copy
    >>> a.append(3.14)
    >>> a
    [42, 3.14]
    >>> b
    [42]
    >>> a is b
    False
    

提交回复
热议问题