2025, Nov 16 17:00
Fixing Python object printing: rename __string__ to __str__ for a readable 6x6 grid output
Learn why your Python class prints the default object representation and fix it: rename __string__ to __str__ to render a clean 6x6 grid with the special method.
When a Python class prints as <module.Class object at 0x...> instead of a nicely formatted string, the usual culprit is a special method that never gets called. This guide walks through a concise case where the output formatting looks correct, the tests are in place, but a single method name prevents everything from working.
Problem
A class builds a 6x6 grid and aims to return a printable view with a separator after the third column and third row. The logic is sound, but printing an instance only shows the default object representation instead of the intended grid.
Code example with the issue
import numpy as npx
class Grid:
CELL_NONE = 0
def __init__(self):
self.flat = npx.array([Grid.CELL_NONE] * 36)
self.matrix = npx.reshape(self.flat, (6, 6))
def __string__(self):
out = ""
for r in range(6):
for c in range(6):
out += f"{str(self.matrix[r, c])} "
if c == 2:
out += "| "
out += "\n"
if r == 2:
out += "------+------\n"
return out
obj = Grid()
print(obj)
The expected result was a clean grid view:
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
What’s going on
The formatting function is named __string__, but Python looks for a method named __str__ when you call print on an object. Because the special method has the wrong name, it never runs, and the default object representation is printed instead.
Fix and corrected code
Rename the method to __str__ so Python knows what to call when printing the instance. The rest of the logic can stay exactly as is.
import numpy as npx
class Grid:
CELL_NONE = 0
def __init__(self):
self.flat = npx.array([Grid.CELL_NONE] * 36)
self.matrix = npx.reshape(self.flat, (6, 6))
def __str__(self):
out = ""
for r in range(6):
for c in range(6):
out += f"{str(self.matrix[r, c])} "
if c == 2:
out += "| "
out += "\n"
if r == 2:
out += "------+------\n"
return out
obj = Grid()
print(obj)
Now printing the instance yields the intended 6x6 layout with the separator exactly where it should be.
Why this matters
Special methods are strict entry points in Python. A tiny typo in their names can silently bypass your logic and send you chasing the wrong issue. In this case, the formatting routine existed and worked, but the language runtime never invoked it.
Conclusion and practical tips
When customizing how an object is printed, implement __str__ with the precise name. If you see the angle-bracketed object string, assume the special method didn’t run and verify the spelling first. Small, focused tests like printing an instance right after construction help catch these issues early and keep your debugging cycle short.