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

后端 未结 3 1967
清酒与你
清酒与你 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:02

    The problem is in this line:

    def __init__(self, data = []):
    

    When you write data = [] to set an empty list as the default value for that argument, Python only creates a list once and uses the same list for every time the method is called without an explicit data argument. In your case, that happens in the creation of both a and b, since you don't give an explicit list to either constructor, so both a and b are using the same object as their data list. Any changes you make to one will be reflected in the other.

    To fix this, I'd suggest replacing the first line of the constructor with

    def __init__(self, data=None):
        if data is None:
            data = []
    

提交回复
热议问题