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

自古美人都是妖i 提交于 2019-12-01 06:20:39

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.

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 = []

When providing default values for a function or method, you generally want to provide immutable objects. If you provide an empty list or an empty dictionary, you'll end up with all calls to that function or method sharing the object.

A good workaround is:

def __init__(self, data = None):
    if data == None:
        self.data = []
    else:
        self.data = data
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!