开发者

Awkward python class behaviour?

开发者 https://www.devze.com 2023-02-01 09:06 出处:网络
I have the following simple code: class Node: pass def make_node(value): n = Node n.value = value r开发者_StackOverflow社区eturn n

I have the following simple code:

class Node:
    pass

def make_node(value):
    n = Node
    n.value = value
    r开发者_StackOverflow社区eturn 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消