Home > other >  I want to print a Matrix in an specific format using the __str__ method
I want to print a Matrix in an specific format using the __str__ method

Time:02-17

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?

CodePudding user response:

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()

CodePudding user response:

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)
  • Related