List.append将所有元素替换为最新元素

时间:2019-04-17 18:41:26

标签: python list

我有一个Node类,其中有一个名称和一个数组,还有一个Graph类,其中应有一个Node对象的数组:

class Node:
    name = ""
    next = []

class Graph:
    nodes = [] # nodes is an array consisting of Node objects 

我制作了一个函数,该函数在传递字符串时将Node对象附加到Graph中。


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)

该函数似乎没有实际附加new_node,而是用最新的new_node对象替换了节点数组中的所有先前元素。

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

这是怎么发生的? new_node是否不是局部变量,并且函数每次迭代时都应该新鲜吗?

2 个答案:

答案 0 :(得分:1)

在类级别设置的属性是静态的-即,由该类的所有实例共享。您可能想要:

class Node:
    def __init__(self):
        self.name = ""
        self.next = []

class Graph:
    def __init__(self):
        self.nodes = []

此外,您需要调用该类以进行实例化-因此需要new_node = Node()graph2 = Graph()

答案 1 :(得分:0)

您需要实际实例化Node和Graph类。

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)

请记住,self是对类的对象实例化的引用。它是类定义的一部分,也是python特定语法。

只需在类的末尾添加()即可从类创建python对象。在Java中,您也必须说new

您定义这样的类:

class Person():
    def __init__(self, some_var):
        self.some_var = some_var
    def some_method(self, msg):
        print("He said:", msg)

然后您可以从中创建一个对象,如下所示:

my_person = Person('my_var')

然后您可以在其中使用如下方法:

my_person.some_method('FooBar')