Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Have a look at the node class below, There you can see wordlist and adjacencyList variables, where these two variables are shared between all instance of the 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']

In the python 3.1.2 version, Is there any way I can continue utilizing the default value for the constructor parameters yet to get both an and b to have their own wordList and adjacencyList variables?

1 Answer

0 votes
by (26.4k points)

Try this following code:

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

Want to learn python? Come and Join the python course.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...