我正在尝试填充对象的字典,每个对象都有一个字符串列表,所有字符串都来自给定的字符串列表。问题是,当我想要替换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中所有对象的字符串,而不仅仅是所需的字符串?
答案 0 :(得分:3)
在messages
的{{1}}内初始化__init__
字段,即Person
,使其成为实例字段。
现在它是一个类级别的字段,因此所有实例共享相同的列表。
答案 1 :(得分:1)
尝试将Create/Read/Update/Deleted , Event information is sent in the Websocket,
giving the web client information that is necessary to send the proper
REST request to fetch exactly the thing the CRUD that happend in server.
放入init:
messages = []
这对我有用!