2

I have a 2d array of objects, where I've assigned each index an object:

for row in range(0, 9):
        for column in range(0, 9):
            self.Matrix[row][column] = Square(row, column) 

where Square() is an object that takes in a specific index. Each Square object has a method constructor (def __str__) that will print a specific text(ex. "KN") for its specific coordinates. I've tried just printing the matrix:

print self.Matrix()

but I end up getting a really long that's something like

[[<__main__.Square object at 0x101936d90>, <__main__.Square object at 0x101936dd0>, <__main__.Square object at 0x101936e10>, .....

How can I print the actual objects instead?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Victor M
  • 603
  • 4
  • 22

2 Answers2

3

This is happening because you're printing the Matrix that contains the Squares. This calls the __str__() for the Matrix class. If you haven't defined a __str__() for that class that returns a string comprising the str() of each of its contained objects, it'll give you the repr() of each of those objects, as defined by their __repr__(). I don't suppose you've defined one. The default is a mere memory location, as you see.

Here's a demo with a stub class:

>>> class A:
...     def __str__(self):
...             return 'a'
...     def __repr__(self):
...             return 'b'
...
>>> print(A())
a
>>> A()
b
>>> [A(), A()]
[b, b]
>>> print([A(), A()])
[b, b]
>>> print(*[A(), A()])
a a

The solution is to either define a specific __str__() for Matrix that returns the str() for each of its contained objects, or define a suitable __repr__() for the Square objects (which should be something that could be passed to eval() to recreate the object, not just something like "KN").

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

You should use __repr__

difference between __repr__ and __str__

class A():
    def __str__(self):
        return "this is __str__"

class B():
    def __repr__(self):
        return "this is __repr__"

a = [A() for one in range(10)]
b = [B() for one in range(10)]

print a
[<__main__.A instance at 0x103e314d0>, <__main__.A instance at 0x103e31488>]
print b
[this is __repr__, this is __repr__]
Community
  • 1
  • 1
holsety
  • 323
  • 1
  • 2
  • 13