Search code examples
pythonconstructordefault-value

Python constructor and default value


Somehow, in the Node class below, the wordList and adjacencyList variable is shared between all instances of Node.

>>> class Node:
...     def __init__(self, wordList = [], adjacencyList = []):
...         self.wordList = wordList
...         self.adjacencyList = adjacencyList
... 
>>> a = Node()
>>> b = Node()
>>> a.wordList.append("hahaha")
>>> b.wordList
['hahaha']
>>> b.adjacencyList.append("hoho")
>>> a.adjacencyList
['hoho']

Is there any way I can keep using the default value (empty list in this case) for the constructor parameters but to get both a and b to have their own wordList and adjacencyList variables?

I am using python 3.1.2.


Solution

  • Mutable default arguments don't generally do what you want. Instead, try this:

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