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?

2
  • 1
    Are you sure you had the parentheses in the print, after Matrix? Because I think you should have gotten an error if you did. Commented Nov 23, 2015 at 7:55
  • You are printing as repr instead of str. How self.Matrix() is implemented? Commented Nov 23, 2015 at 7:57

2 Answers 2

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").

Sign up to request clarification or add additional context in comments.

Comments

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__]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.