此代码的最有效和最好的版本是什么?
What is the most efficient and well presented version of this code?
我正在尝试制作一个 class,它创建空棋盘对象作为棋盘游戏项目的一部分。这是我想出的:
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
嗯,你的 class 可以改进。正如评论中指出的那样, board
应该是一个实例属性,而不是 class 可以通过列表理解简洁地启动的属性。此外,正确使用 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
我正在尝试制作一个 class,它创建空棋盘对象作为棋盘游戏项目的一部分。这是我想出的:
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
嗯,你的 class 可以改进。正如评论中指出的那样, board
应该是一个实例属性,而不是 class 可以通过列表理解简洁地启动的属性。此外,正确使用 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