私は文字列のリストを持つオブジェクトのdictをすべて指定した文字列のリストから入力しようとしています。問題は、dictの1つの要素を置き換えたい場合、すべての要素が変更されることです。Pythonで単一のdict要素を置き換える
Personクラス:
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のすべてのオブジェクトに追加される文字列ですか?
もちろん、同じリストに*追加している、つまりあなたのクラスで定義したリストに 'messages = []'として追加しているからです。これは*クラスレベルの属性です* shared *すべてのインスタンス*によって。 –