Home » Python » class – How can I create an object's property inline with Python?-Exceptionshub

class – How can I create an object's property inline with Python?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


I’m working on an exercise on the Exercism website, and basically what it requires is that you create a Matrix object that takes an argument of the form '1 2 3\n4 5 6\n7 8 9' and then has two methods (row and column) that returns the numbers in that specific matrix’s rows and columns (given an argument for which row or column to return). Here is my code, which already works:

class Matrix:
    def __init__(self, matrix_string):
        self.matrix_rows = []
        for row in matrix_string.split('\n'):
            self.matrix_rows.append(row.split(' '))

    def row(self, index):
        return [int(num) for num in self.matrix_rows[index - 1]]

    def column(self, index):
        return [int(num) for num in list(zip(*self.matrix_rows))[index - 1]]

But I got some feedback from one of the website mentors that said this:

Nice job with your solution!

Both L8 and L11 require cleaning to turn strings into ints. Is there a
better place to do this work?

Can self.matrix_rows be created inline, i.e. without the loop on L4?

I’m still thinking about the first comment (L8 and L11), but I’m confused on the second comment about L4, because I’m not sure what he means by creating self.matrix_rows “inline.” I assumed it was a term with a specific meaning, and I found this thread: How to create inline objects with properties in Python? but I’m not sure if that’s the same thing as my question. I don’t want to create an inline object, but just an inline property of an object…I think?

Any suggestions that would help me decrypt his comments would be appreciated!

How to&Answers: