I'm trying to create classes for a network, but data is getting shared between nodes. I do not want data to be shared between nodes. I am not sure why this is happening. I have this code so far:
class Node:
def __init__(self, data=dict()):
self.data = data
class Network:
def __init__(self):
self.nodes = dict()
def add_node(self, node_id, data=dict()):
self.nodes[node_id] = Node(data=data)
Depending on how I add a node to the network, there seems to be an issue of data being shared between nodes. I demonstrate this below:
Firstly, if I add nodes without data, then insert data to the nodes, the data gets shared between the nodes.
nx = Network()
nx.add_node('a')
nx.add_node('b')
nx.nodes['a'].data['numbers'] = 123
nx.nodes['a'].data, nx.nodes['b'].data
Outputs:
({'numbers': 123}, {'numbers': 123})
So without adding data to the 'b' node, somehow its data gets populated with the data added to the 'a' node.
Now, if I avoid the add_node
method, like this, I get a different outcome:
nx.nodes['c'] = Node(data = {'foo': 291284})
nx.nodes['c'].data
I get this output:
{'foo': 291284}
And nodes 'a' and 'b' remain as they were:
nx.nodes['a'].data, nx.nodes['b'].data
Outputs:
({'numbers': 123}, {'numbers': 123}
Where am I going wrong here? If I add data to node 'a', I only want node 'a' to have that data, it should not get shared.