I have a Node class, which has a name and an array in it, and a Graph class which should have an array of Node objects:
class Node:
name = ""
next = []
class Graph:
nodes = [] # nodes is an array consisting of Node objects
I've made a function which appends a Node object into the Graph when passed a string.
def add_new(self, new_name):
new_node = Node
new_node.name = new_name
self.nodes.append(new_node)
print("New node given name: ", new_name)
print("New length of nodes: ", len(self.nodes))
graph2 = Graph
add_new(graph2, "Jim")
add_new(graph2, "Dwight")
add_new(graph2, "Andy")
print("Node names: ")
for i in range(0,3):
print(graph2.nodes[i].name)
Instead of actually appending the new_node, the function seems to replace all the previous elements of the node array with the latest new_node object.
python -u "c:\Users\Vishnu\CS-Project\why.py"
New node given name: Jim
New length of nodes: 1
New node given name: Dwight
New length of nodes: 2
New node given name: Andy
New length of nodes: 3
Node names:
Andy
Andy
Andy
How does this happen? Isn't new_node a local variable and shouldn't it be fresh every iteration of the function?