class EditorState:
def __init__(self, content):
self.content = content
class Editor:
def __init__(self):
self.content = ""
def __str__(self):
return f'{self.content}'
def setContent(self, value):
self.content = value
def createContent(self):
return EditorState(self.content)
def restore(self, new_value):
self.content = new_value
def getcontent(self):
return self.content
class History:
def __init__(self):
self.history = []
def __repr__(self):
return self.history
def push(self, value):
self.history.append(value)
def remove(self):
my_list = self.history
my_list.pop()
last_index = my_list[-1]
return last_index
def getvalue(self):
my_list = self.history
return self.history
editor = Editor()
history = History()
editor.setContent("a")
history.push(editor.createContent())
editor.setContent("b")
history.push(editor.createContent())
editor.setContent("c")
history.push(editor.createContent())
editor.setContent("D")
history.push(editor.createContent())
editor.restore(history.remove())
print(history.getvalue())
print(editor.getcontent())
当我检查列表中的项目时得到的输出:[< main .EditorState object at 0x0000017B77360040>, < main .EditorState object at 0x0000017B773600D0>, < main .EditorState object at 0x0000017B77360130>]
我想要的输出:[a,b,c]
我已经学会了如何在 java 中使用 Memento 模式,我想用 python 尝试这个模式。我确实工作,但问题是,当我从历史记录类的列表中返回最后一项时,它一直向我显示它的 id 而不是值。当我使用 getvalue() 方法打印列表时也是如此。
我尝试使用魔术方法 sush 作为str或repr但它不起作用,我也尝试将属性设置为变量但没有结果。