I'm running into trouble with some Python stuff. I have a list that has seven copies of a class and I am intending to change just the values of one of them but whenever I do it changes the value for all.
Here is the class:
class Node:
previous = -1
distFromSrc = 1000000
visited = False
And here is how I create the list:
def createNodeTable(network):
nodeTable = []
for line in network:
nodeTable.append(Node)
return nodeTable
'network' is a list of length 7 so when I print the 'nodeTable[x].visited' before I attempt to make any changes to the values I get 'False' for every one.
If I call the following function however all of the '.visited' values change to false not just the one I am intending to change.
Whatever 'currentNode' is changed to I get the same issue:
def setVisited(currentNode, nodeTable):
nodeTable[currentNode].visited = True
return nodeTable
Is there an issue with the setVisited function or is it to with the nodeTable? I don't even know where to start to try to fix this.
nodeTable.append(Node)
The problem lies in that line. What you are doing there is that you append the type (or class) to the list. So you end up with a list of seven times the exact same type reference.
What you should do instead is creating instances of said type. You can do that by calling it.
nodeTable.append(Node())
should't
def createNodeTable(network):
nodeTable = []
for line in network:
nodeTable.append(Node)
return nodeTable
be:
def createNodeTable(network):
nodeTable = []
for line in network:
nodeTable.append(Node())
return nodeTable
You want 7 different instances appended to nodeTable, not the same class object 7 times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With