【发布时间】:2021-04-04 14:33:52
【问题描述】:
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 对象位于 0x0000017B77360130>]
我想要的输出:[a,b,c]
我已经学会了如何在 java 中使用 Memento 模式,我想用 python 试试这个模式。我确实工作,但问题是当我从历史类的列表中返回最后一项时,它一直向我显示它的 id 而不是值。当我使用 getvalue() 方法打印列表时也是如此。
我尝试使用魔法方法 sush 作为 str 或 repr 但它不起作用,我也尝试将属性设置为变量但没有结果。
【问题讨论】:
-
您显示课程
EditorState和Editor。他们与History类有什么关系?在类History方法remove中弹出(删除)最后一个条目,然后返回现在新的最后一个条目。它没有返回最后一个条目。这真的是你想要的吗?为什么需要引入一个新变量my_list?你是什么意思“它一直向我展示它的身份”?什么是“身份证”?向我们展示您用于测试此类的代码、您得到的结果以及您期望的 精确 值。 -
Editor 从用户那里获取值并将其保存在 EditorState 类中。然后保存在 EditorState 类中的值将添加到我们在 History 类中的列表中。历史类用于我们将创建撤消的情况。我创建了我的列表只是为了尝试解决问题,但这实际上是不必要的。
-
当我使用我创建的 remove 方法和 restore 方法时,我会得到我在最后一个值之前添加的值。然后当我调用 getContent 方法时,我应该得到值,但我得到的是它的 ID。 <__main__.editorstate>
-
1.您应该编辑问题,添加您使用的导致异常的最少代码。 2、你应该指定
remove的期望值是什么(不要只说“我在最后一个值之前添加的最后一个值”——实际上指定实际值,例如7,这样就没有误解) . 3. 理想情况下,您应该在编辑的问题中包含异常的完整堆栈跟踪。这是给你的一个问题:你从一个新初始化的History实例开始,然后执行一个push调用,然后是一个remove调用。您希望它返回什么?
标签: python list class design-patterns memento