[Python] How does converting an object to a string work in python?

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to get a class that I wrote to print the way I want it to print. I've used python before, but it's been a while, so I looked at some examples, and I'm not sure what I'm doing wrong.

    Currently, my (relevant) code within the class looks like this (the file is called 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


    I wanted to just check that it would come out as I wanted, as it's good practice to test each function as I write it. In a separate testing file (stored within the same folder), I wrote the following code to make sure everything came out the way I wanted it to, and there were no off-by-one errors, or using numpy functions incorrectly:

    from board import Board

    my_board = Board()
    print(my_board)


    As it turned out, I had a bigger problem on my hands than an off-by-one error, because it just prints <board.Board object at {hex address}>. I didn't think I'd lost that much python knowledge, but my debugger seems to just skip over the __str__() function entirely. What am I doing wrong??

    By the way, the expected result was for it to print

    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

    Continue reading...

Compartilhe esta Página