I have a Node class. Then I'm building a chain of Nodes. They are connected with one another via self.prev_node and self.next_nodes, also the Chain : self.last holds a link to the last element of the chain. I'm using a method like this to add a new node :
class Node(object):
def __init__(self, next_nodes=[], prev_node=None):
self.next_nodes = next_nodes
self.prev_node = prev_node
class Chain:
def __init__(self):
self.start = Node()
self.last = self.start
def add_node(self, node):
node.prev_node = self.last
self.last.next_nodes.append(node)
self.last = node
The problem is that if I add several nodes :
c.start.next_nodes
[Node:2, Node:3, Node:4]
c.start.next_nodes[0].next_nodes
[Node:2, Node:3, Node:4]
instead it should be :
c.start.next_nodes
[Node:2]
c.start.next_nodes[0].next_nodes
[Node:3]
For some reason the next_nodes list seems to be duplicate/the-same.
What I'm doing wrong ?
You're passing mutable "[]" in init as a parameter.
So each node you make is referring to the same memory location thus ending up with all same "next_nodes".