Python list append causes strange result

前端 未结 5 1299
执念已碎
执念已碎 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:48

    As many have already mentioned it, you end up having two references on the same list. Modifying the list by one reference of by the other just modify the list.

    Here is an illustration to make things more clear if needed:

    Shared reference

    • Step "A" is just after

      self.a = [(1,2), (3,4)]
      
    • Step "A" is just after

      self.b = self.a
      
    • Step "C" is just after

      self.a.append((5,6))
      

提交回复
热议问题