0

I wanna print an all zeros matrix this way:

0 0 0
0 0 0
0 0 0

In order to do that i gotta use the __str__ method. This is what I've gotten so far:

class Matrix:
    def __init__(self, m, n):
        self.rows = m  # rows
        self.cols = n  # columns
        self.matrix = []  # creates an array
        for i in range(self.rows):
            self.matrix.append([0 for i in range(self.cols)])

    def __str__(self):
        # string = ""
        for element in self.matrix:
            return print(*element)


a_matrix = Matrix(3, 3)
print(a_matrix)

But when i run the code, there's an error:

Traceback (most recent call last):
  File "C:\Users\DELL USER\Google Drive\Programacion\Negocios\main.py", line 72, in <module>
    print(a_matrix)
TypeError: __str__ returned non-string (type NoneType)
0 0 0

Process finished with exit code 1

Note how i'm using return print(*element), usually, out of the str method it works just fine but when i use it that way, it stops working. Is there a way i can covert that print to a string so i can get rid of the error?

ronny
  • 41
  • 7
  • 1
    `__str__` shouldn't print anything. It should return a *string*. – chepner Feb 16 '22 at 19:57
  • Does this answer your question? [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Pranav Hosangadi Feb 16 '22 at 20:03

2 Answers2

1

def __str__(self): needs to return a string. You can do this:

class Matrix:
    def __init__(self, n, m):
        self.matrix = []
        for i in range(n):
            self.matrix.append([0 for i in range(m)])

    def __str__(self):
        outStr = ""
        for i in range(len(self.matrix)):
            for c in self.matrix[i]:
                outStr += str(c)
            outStr += "\n"
        return outStr

matrix = Matrix(3, 3)
print(matrix)
fbi open_up
  • 101
  • 1
  • 7
0

a_matrix has a property "matrix" print that?

class Matrix:
    def __init__(self, m, n):
        self.rows = m  # rows
        self.cols = n  # columns
        self.matrix = []  # creates an array
        for i in range(self.rows):
            self.matrix.append([0 for i in range(self.cols)])

    def __str__(self):
        # string = ""
        for element in self.matrix:
            return print(*element)


a_matrix = Matrix(3, 3)

for i in range(a_matrix.rows):
    for j in range(a_matrix.cols): 
        print(a_matrix.matrix[i][j], end = " ")
    print()
Shawn Ramirez
  • 796
  • 1
  • 5
  • 10