[英]print matrix object in python
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: 您可以为您的课程实现
__repr__
魔术方法 :
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)
). 这将使用
self.board
的表示形式作为类实例的表示形式(即print(Board())
与print(Board().board)
)。
Note also that you should use class attributes explicitly, eg: 还要注意,您应该显式使用类属性,例如:
self.board = np.zeros((Board.BOARD_SIZE, Board.BOARD_SIZE))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.