You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python对象转字符串机制及自定义类打印格式问题排查

问题:自定义Board类无法按预期格式打印

我希望自己编写的Board类能按照预期格式打印。之前用过Python,但间隔了一段时间,参考示例后仍未找到问题所在。

当前代码

board.py文件内容

import numpy as np

class Board:
    
    CELL_EMPTY = 0

    def __init__(self):
        self.board = np.array([Board.CELL_EMPTY] * 36)        
        self.board_2d = np.reshape(self.board,(6,6))

    def __string__(self):
        resultStr = ""
        for i in range(6):
            for j in range(6):
                resultStr += f'{str(self.board_2d[i, j])} '
                if j == 2:
                    resultStr += '| '
            resultStr += '\n'
            if i == 2:
                resultStr += '------+------\n'
        return resultStr

测试文件内容

from board import Board

my_board = Board()
print(my_board)

问题现象

实际输出为<board.Board object at {hex address}>,调试器完全跳过了自定义的字符串方法,无法得到预期格式的打印结果。

预期打印结果

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 0 0 | 0 0 0
0 0 0 | 0 0 0

解决方案

问题出在方法名错误:Python中用于自定义对象可读字符串表示的特殊方法是__str__,而非你写的__string__。

修改方法名即可解决问题,修正后的__str__方法代码如下:

def __str__(self):
    resultStr = ""
    for i in range(6):
        for j in range(6):
            resultStr += f'{str(self.board_2d[i, j])} '
            if j == 2:
                resultStr += '| '
        resultStr += '\n'
        if i == 2:
            resultStr += '------+------\n'
    return resultStr

当调用print(my_board)时,Python会自动调用对象的__str__方法获取字符串表示,之前因方法名错误,Python只能使用默认的对象格式输出。

内容的提问来源于stack exchange,提问作者Y F-N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:27:10