socks
socks

Reputation: 105

Awkward python class behaviour?

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?

Upvotes: 1

Views: 114

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 994619

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.

Upvotes: 5

Related Questions