Skip to main content
 首页 » 编程设计

python之打印数据结构

2025年05月04日16Free-Thinker

我正在编写数独解算器,作为其中的一部分,我正在创建一个类来表示数独板。该类的部分功能是能够自行打印。现在我有一个方法 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).

根据您的描述,这听起来不像您的打印目标。