替换Python中的单个dict元素

替换Python中的单个dict元素,python,dictionary,Python,Dictionary,我试图用每个对象都有一个字符串列表来填充对象的dict,所有对象都来自给定的字符串列表。问题是,当我想替换dict的单个元素时,每个元素都会发生变化 人员类别: class Person: messages = [] def __init__(self, p): self.name = p def add_message(self, m_text): self.messages.append(m_text) 主要代码: chat_m

我试图用每个对象都有一个字符串列表来填充对象的dict,所有对象都来自给定的字符串列表。问题是,当我想替换dict的单个元素时,每个元素都会发生变化

人员类别:

class Person:

    messages = []

    def __init__(self, p):
        self.name = p

    def add_message(self, m_text):
        self.messages.append(m_text)
主要代码:

chat_messages_list = ["Eva: Eva's first text", "Eva: Eva's second text", "Eva: Eva's third text",
                      "Harry: Harry's first text", "Harry: Harry's second text", "Harry: Harry's third text",
                      "Ellis: Ellis' first text", "Ellis: Ellis' second text", "Ellis: Ellis' third text"]
dict_persons = {}

for element in chat_messages_list:

    split_messages = element.split(": ")
    name = split_messages[0]
    message_text = split_messages[1]

    # Create Person in list if not already exists
    if name not in dict_persons:
        dict_persons[name] = Person(name)

    person = dict_persons[name]

    # THE PROBLEM: Following line will add message_text to EVERY Person in dict_persons
    person.add_message(message_text)

for key, value in dict_persons.items():
    print("{0}: {1}".format(key, value.messages))
预期结果:

Eva: ["Eva's first text", "Eva's second text", "Eva's third text"]
Harry: ["Harry's first text", "Harry's second text", "Harry's third text"]
Ellis: ["Ellis' first text", "Ellis' second text", "Ellis' third text"]
实际结果:

Eva: ["Eva's first text", "Eva's second text", "Eva's third text", "Harry's first text", "Harry's second text", "Harry's third text", "Ellis' first text", "Ellis' second text", "Ellis' third text"]
Ellis: ["Eva's first text", "Eva's second text", "Eva's third text", "Harry's first text", "Harry's second text", "Harry's third text", "Ellis' first text", "Ellis' second text", "Ellis' third text"]
Harry: ["Eva's first text", "Eva's second text", "Eva's third text", "Harry's first text", "Harry's second text", "Harry's third text", "Ellis' first text", "Ellis' second text", "Ellis' third text"]

Wy是添加到dict中所有对象的字符串,而不是所需的字符串吗?

尝试将
消息=[]
放在init中:

class Person:

    def __init__(self, p):
        self.name = p
        self.messages = []

    def add_message(self, m_text):
        self.messages.append(m_text)

这对我有用

尝试将
消息=[]
放在您的init中:

class Person:

    def __init__(self, p):
        self.name = p
        self.messages = []

    def add_message(self, m_text):
        self.messages.append(m_text)

这对我有用

初始化
人员的
\uuuuu init\uuuuu
中的
消息
字段,即
self.messages=[]
使其成为实例字段。

现在它是一个类级字段,因此所有实例共享同一个列表。

初始化
消息
位于
人的
\uuuuuuuuu
中的
初始化
字段,即
self.messages=[]
使其成为实例字段。

现在它是一个类级字段,因此所有实例共享同一个列表。

是的,当然,因为您要附加到同一个列表,也就是说,您要附加到您在类中定义为
messages=[]
的列表,这是所有实例共享的类级属性。是的,当然,因为您要附加到同一个列表,也就是说,您将添加到在类中定义为
messages=[]
的列表中,该列表是所有实例共享的类级属性。