1

I have the following simple code:

class Node:
 pass
def make_node(value):
 n = Node
 n.value = value
 return n
if __name__ == '__main__':
 list = range(100)
 random.shuffle(list)
 nodes = []
 for i in range(len(list)):
 nodes.append(make_node(list[i]))
 for n in nodes:
 print n.value

Upon printing the value at each of the nodes, they are all identical. It seems that each "new node" i built simply overwrites the value of all of the previous ones. Why are these not being set completely separately, and how can I fix it?

Katriel
124k19 gold badges141 silver badges172 bronze badges
asked Dec 26, 2010 at 3:02

1 Answer 1

5

I think you want to call the Node constructor:

 n = Node()

Otherwise, the assignment to n.value is the same as assigning to Node.value, which sets an attribute of the class, not the object you wanted to create. By returning the Node class object itself, your nodes list contains a bunch of references to the same Node class object.

answered Dec 26, 2010 at 3:06
Sign up to request clarification or add additional context in comments.

1 Comment

You may be able to infer that you're not the only one who's made this mistake. :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.