What am I doing wrong? Python object instantiation keeping data from previous instantiation?

后端 未结 3 1817
清酒与你
清酒与你 2021-01-11 19:56

Can someone point out to me what I\'m doing wrong or where my understanding is wrong?

To me, it seems like the code below which instantiates two objects should have

3条回答
  •  一向
    一向 (楼主)
    2021-01-11 20:13

    You can't use an mutable object as a default value. All objects will share the same mutable object.

    Do this.

    class Node:
        def __init__(self, data = None):
            self.data = data if data is not None else []
    

    When you create the class definition, it creates the [] list object. Every time you create an instance of the class it uses the same list object as a default value.

提交回复
热议问题