Не могу посмотреть список «матрица» - PullRequest
0 голосов
/ 18 ноября 2018

У меня проблема с классом "CellList", поэтому я хочу напечатать список "matrix". Но когда я распечатываю этот список, мой Pycharm отображает "[[myfile.Cell объект в 0x0034 ...] [myfile.Cell объект в 0x0034 ...], ...]"

class Cell:

    def __init__(self, row: int, col: int, state=0):
        self.state = state
        self.row = row
        self.col = col

    def is_alive(self) -> bool:
        return self.state


class CellList():

    @classmethod
    def from_file(cls, filename):
        with open(filename, 'r') as f:

            r = 0
            matrix = []

            for line in f:
                c = 0
                arr = []
                for ch in line:
                    if ch == '0' or ch == '1':
                        arr.append(Cell(r, c, int(ch)))
                    c += 1
                matrix.append(arr)
                r += 1

        cls.r_max = r
        cls.c_max = c - 1
        cls.matrix = matrix

        return CellList(cls.r_max, cls.c_max, cls.matrix)

1 Ответ

0 голосов
/ 18 ноября 2018

Для того, чтобы объект представлял себя не по умолчанию, вы должны отказаться от метода __repr__.это может быть такой метод:

class Cell:
    # ....
    def __repr__(self):
        # python >= 3.6
        return f'Cell(state={self.state}, row={self.row}, col={self.col})'
        # python < 3.6
        # return 'Cell(state={0.state}, row={0.row}, col={0.col})'.format(self)

, и пока вы занимаетесь этим, вы также можете реализовать __str__ (таким же образом?).

...