python - 如何取消最后调用的方法?

标签 python python-3.x

class Minobot:
    def __init__(self):
        self.x,self.y = 0, 0
        self.angle = 90

    def forward(self, d):
        angle = radians(90-self.angle)
        nx, ny = self.x + d * cos(angle), self.y + d * sin(angle)
        self.x, self.y = nx, ny

    def right(self):
        self.angle += 90

    def left(self):
        self.angle -= 90

    def coordinates(self):
        return round(self.x, 1), round(self.y, 1)

    def manhattan_distance(self):
        return int(abs(round(self.x, 1))+abs(round(self.y, 1)))

    def cancel(self):
        ????

现在我需要向此类中添加另一个方法来取消上次调用的方法。 例如: a.forward(2) => a.right() => a.cancel() 这将在使用 a.right() 之前设置 Minobot。

最佳答案

您不能取消最后的操作,除非您存储它。

如果你存储最后一个 Action ,你可以反转它。因为一旦你采取行动就知道反向行动,你可以直接存储反向行动。

让您的 Minibot 实例有一个 .reverse_action 属性,它是要调用的方法和要传递的参数的元组。

所以

def left(self):
   # Note how methods can just be stored in variables.
   self.reverse_action = (self.right, ())
   ...

def forward(self, distance):
   # Forward is its own reverse with a negative distance.
   self.reverse_action = (self.forward, (-distance,))

def revert_last(self):
   if self.reverse_action:
      (method, args) = self.reverse_action
      method(*args)  # Call the stored method, passing stored args.
      self.reverse_action = None  # Used it up.

这有一个明显的缺点,那就是只能恢复最后一个操作。如果您为您执行的每个操作存储了一个列表,您可以从中.pop() 并还原操作,只要在列表。

如果您正在执行大量操作并且内存受限,则您只能存储最后几个操作。 (搜索术语:“撤消缓冲区”、“循环缓冲区”、“事件源”。)

另一种方法是存储之前的状态,即坐标、航向等。撤消上一个操作只是切换到之前的状态:

def save_state(self):
  self.previous_state = (self.x, self.y, self.angle)
  # Or: self.previous_states_list.append(...)

def restore_previous_state(self):
  (self.x, self.y, self.angle) = self.previous_state
  # Or: ... = self.previous_states_list.pop()

def left(self): 
  self.save_state()
  ...

这种方法没有舍入错误等问题。不过它需要更多内存,尤其是当您的状态变大时,以及当您想要保存以前状态的完整历史时。

关于python - 如何取消最后调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173774/

相关文章:

python - python 中的条件日志记录

python - 如何让 python 3.x 在网络浏览器中输入文本

python - python 中的 max() 和 min()

python - 查找更改整数以匹配列表中其他整数的最小移动次数

python - 返回从几个月前开始的月份数字列表

python - panda3d python 导入错误

python - matplotlib.pyplot 错误 "ImportError: cannot import name ' _path'"

python - 如何增加 flask 形式的 bool 字段的大小?

python - 如何使用元组填充数据框?

Python 程序在 Windows 上失败但在 Linux 上不会