我正在编写数独解算器,作为其中的一部分,我正在创建一个类来表示数独板。该类的部分功能是能够自行打印。现在我有一个方法 PrintBoard 作为我类(class)的一部分。所以我会这样使用它:
myBoard.PrintBoard()
但我在想;有没有办法覆盖 python 的打印,以便:
print(myBoard)
运行 PrintBoard 方法?
最佳答案
是的。看看 __str__
方法。
您还可以使用 __repr__
方法,但如文档中所述:
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).
根据您的描述,这听起来不像您的打印目标。
关于python - 打印数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527386/