Emre
Emre

Reputation: 81

Change default print for class object - Python

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

Upvotes: 1

Views: 2857

Answers (2)

Solomon Ucko
Solomon Ucko

Reputation: 6109

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.

Upvotes: 3

M Dillon
M Dillon

Reputation: 164

Implement the __str__ method to print something nicely by default.

Upvotes: 0

Related Questions