什么是此代码的最有效和最完整的版本?

时间:2018-08-20 15:56:02

标签: python pep8 coding-efficiency

我正在尝试创建一个可创建空棋盘对象的类,作为棋盘游戏项目的一部分。这是我想出的:

class Board:
    board = []
    # Initially the board is empty

    def __init__(self, size=9):
        # If n is the size of the board
        # Each line is a list of n colums
        # Each column is initially set as a list of n empty squares
        for line in range(size):
            list = []
            for columns in range(size):
                list.append("O")
            self.board.append(list)
        return None

    def __repr__(self):
        # Lines separator is '\n'
        # Columns separator is ' '
        repr = ''
        for n_line in range(len(self.board)):
            for n_column in range(len(self.board[n_line])):
                repr += self.board[n_line][n_column] + ' '
            repr += '\n'
        return repr

1 个答案:

答案 0 :(得分:1)

嗯,您的课程可以提高。如评论中所指出的,board应该是实例属性,而不是可以通过列表理解来明确启动的类属性。此外,正确使用str方法也会大大缩短您的__repr__

class Board:
    # don't make board a class attribute

    def __init__(self, size=9):
        self.board = [["O"] * size for _ in range(size)]

    def __repr__(self):
        return '\n'.join(' '.join(line) for line in self.board)
        # Or more fanciful
        # return '\n'.join(map(' '.join, self.board))

>>> b = Board()
>>> b
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O
O O O O O O O O O