1

I have a class Board.

class Board:
    # Initialize empty n x n board
    def __init__(self, n):
        self.board = [[0]*n for x in range(n)]
        self.size_n = n
    # ...

I want to be able to print an object of this class with the default print(board_obj) function such that I get this output:

[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]

I tried this but it prints the matrix in one line, which I don't want:

# Represent the class object as its board
def __repr__(self):
    return repr(self.board)

Wrong output:

[[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]]

I also do not want a custom class method like below:

# Custom print
def print_board(self):
    for row in self.board:
        print row
Emre
  • 81
  • 8

2 Answers2

3

How about:

def __str__(self):
    return '\n'.join(map(repr, self.board))

You should use __str__ for the human-readable version, and __repr__ for the unambigous version.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
  • 3
    I would avoid making `__repr__` the easy-to-read option. There's an in depth discussion [here](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python), but the main point is that `__repr__` should be unambiguous, and `__str__` should be human readable. – M Dillon Mar 14 '18 at 13:18
0

Implement the __str__ method to print something nicely by default.

M Dillon
  • 164
  • 1
  • 8