I am making a board class and want a method that will allow me to print it as a matrix:
import numpy as np
class Board(object):
BOARD_SIZE = 8+1
BOARD_EDGE = range(BOARD_SIZE)
def __init__(self):
self.board = np.zeros( (BOARD_SIZE, BOARD_SIZE) )
for i in BOARD_EDGE:
self.board[i, 0] = i
self.board[0, i] = i
How do I make a method to print the board similar to this:
board = np.zeros( (8,8) )
print board
[[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0.]]
You can implement the __repr__
magic method for your class:
class Board(object):
# existing code here...
def __repr__(self):
return repr(self.board)
This will use the representation of the self.board
as the representation for the class instance (ie print(Board())
becomes the same as print(Board().board)
).
Note also that you should use class attributes explicitly, eg:
self.board = np.zeros((Board.BOARD_SIZE, Board.BOARD_SIZE))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.