在课堂上移动信息

时间:2012-12-26 21:38:52

标签: python

我想编写一个函数,它将用户插入函数plays中的参数move()的所有字符串保存到函数undo_str中的字符串undo()。 我在这里错过了什么?

class Sokoban:
        def __init__(self, board):
                self.board = board.copy()

        def move(self, plays):
             ............

        def undo(self):
                undo_str=""
                undo_str=undo_str[:]+plays
                self.undo=undo_str[:-1]

1 个答案:

答案 0 :(得分:1)

我希望这会有所帮助。如果你添加一些类属性来保持信息,它应该相当容易。这里init方法将sokoban.plays和sokoban undo_str初始化为空字符串。 sokoban.move('string')会将sokoban.plays更改为'string',而sokoban.undo_str()会将当前的sokoban.plays添加到sokoban.undo_str

class Sokoban:
    def __init__(self, board):
            self.board = board.copy()
            self.plays = ''
            self.undo_str = ''

    def move(self, plays):
         self.plays = plays
         ............

    def undo(self):
            undo_str=undo_str[:]+self.plays


sokoban = Sokoban(board)
sokoban.move('play1')
sokoban.undo()
sokoban.move('play2')
sokoban.undo()

In: sokoban.plays 
Out 'play2'

In: sokoban.undo_str
Out: 'play1play2'

(注意我摆脱了'self.undo = self.undo_str [: - 1]'这一行。这会与函数self.undo冲突。)