List.append replaces all the elements with the latest element
我有一个节点类,其中有一个名称和一个数组,还有一个图形类,其中应该有一个节点对象数组:
1 2 3 4 5 6 | class Node: name ="" next = [] class Graph: nodes = [] # nodes is an array consisting of Node objects |
我做了一个函数,当传递一个字符串时,它将一个节点对象附加到图中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def add_new(self, new_name): new_node = Node new_node.name = new_name self.nodes.append(new_node) print("New node given name:", new_name) print("New length of nodes:", len(self.nodes)) graph2 = Graph add_new(graph2,"Jim") add_new(graph2,"Dwight") add_new(graph2,"Andy") print("Node names:") for i in range(0,3): print(graph2.nodes[i].name) |
该函数不是实际附加新的节点,而是用最新的新节点对象替换节点数组的所有以前的元素。
1 2 3 4 5 6 7 8 9 10 11 | python -u"c:\Users\Vishnu\CS-Project\why.py" New node given name: Jim New length of nodes: 1 New node given name: Dwight New length of nodes: 2 New node given name: Andy New length of nodes: 3 Node names: Andy Andy Andy |
这是怎么发生的?新节点不是局部变量吗?它不应该是函数每次迭代的新变量吗?
在类级别设置的属性是静态的——也就是说,由类的所有实例共享。你可能想要:
1 2 3 4 5 6 7 8 | class Node: def __init__(self): self.name ="" self.next = [] class Graph: def __init__(self): self.nodes = [] |
此外,还需要调用类来实例化,因此需要
您需要实际地实例化节点和图形类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Node: def __init__(self, name): self.name = name class Graph: def __init__(self): self.nodes = list() def add_new(self, new_name): new_node = Node(new_name) self.nodes.append(new_node) print("New node given name:", new_name) print("New length of nodes:", len(self.nodes)) graph2 = Graph() graph2.add_new("Jim") graph2.add_new("Dwight") graph2.add_new("Andy") print("Node names:") for i in range(0,3): print(graph2.nodes[i].name) |
记住,
从类中创建一个python对象,只需将
您定义的类如下:
1 2 3 4 5 | class Person(): def __init__(self, some_var): self.some_var = some_var def some_method(self, msg): print("He said:", msg) |
然后从中创建一个对象,如下所示:
1 | my_person = Person('my_var') |
然后您可以在其中使用如下方法:
1 | my_person.some_method('FooBar') |