Why does += behave unexpectedly on lists?

后端 未结 8 1242
春和景丽
春和景丽 2020-11-21 07:20

The += operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?

class foo:  
     bar = []
            


        
8条回答
  •  长情又很酷
    2020-11-21 08:01

    The problem here is, bar is defined as a class attribute, not an instance variable.

    In foo, the class attribute is modified in the init method, that's why all instances are affected.

    In foo2, an instance variable is defined using the (empty) class attribute, and every instance gets its own bar.

    The "correct" implementation would be:

    class foo:
        def __init__(self, x):
            self.bar = [x]
    

    Of course, class attributes are completely legal. In fact, you can access and modify them without creating an instance of the class like this:

    class foo:
        bar = []
    
    foo.bar = [x]
    

提交回复
热议问题