Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of classes issue

Tags:

python

list

class

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.

like image 345
Thomas Mitchell Avatar asked Aug 29 '26 22:08

Thomas Mitchell


2 Answers

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())
like image 124
poke Avatar answered Aug 31 '26 15:08

poke


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.

like image 39
Mike Corcoran Avatar answered Aug 31 '26 15:08

Mike Corcoran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!