Python list append causes strange result

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

    Because self.a and self.b are actually references to the same list object.

    If you want to modify one without changing the other, try this

    class SomeClass(object):
        # a = []
        # b = [] # these two class member not necessary in this code
        def __init__(self, *args, **kwargs):
            self.a = [(1,2), (3,4)]
            self.b = list(self.a) # copy to a new list
            self.a.append((5,6))
            print self.b
    
    SomeClass()
    

提交回复
热议问题