System Down
System Down

Reputation: 6270

Printing a Data Structure

I'm programming a Sudoku solver, and as part of that I'm creating a class to represent a Sudoku board. Part of the functionality of the class is the ability to print itself. Right now I have a method PrintBoard as part of my class. So I would use it like this:

myBoard.PrintBoard()

But I was thinking; is there a way to override python's print so that:

print(myBoard)

runs the PrintBoard method?

Upvotes: 1

Views: 1064

Answers (2)

David Alber
David Alber

Reputation: 18121

Yes. Have a look at the __str__ method.

You can also use the __repr__ method, but as stated in the documentation:

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

From your description, that does not sound like your goal for printing.

Upvotes: 8

TJD
TJD

Reputation: 11906

You can implement the __repr__ or __str__ operations for your class

Upvotes: 2

Related Questions