Python list append causes strange result

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

    self.b = self.a isn't copying the list. It's assigning the reference to that list, so both attributes point at the same object. If you modify it via one reference, you'll see the change via the other one too.

    You can use copy.copy(the_list) to get the proper copy. Or copy.deepcopy(the_list) if you need the references below also updated.

提交回复
热议问题