将定义中的信息放入类方法__str__中

时间:2016-12-13 01:09:26

标签: python list class

我正在尝试将此函数的信息输入到类方法 str

def display(self)`:
        '''
        to see the grid and check to see if everything is working
        '''

    # header
    print("  0   1")
    # grid
    print('-'*8)
    for i, row in enumerate(self.grid):

        print('0|'.format(i), end='') #prints the 0 and 1 on the left

        for cell in row: 
            print('{:2s}|'.format(str(cell)), end="")

        print()
        print('-'*8)

但我希望此信息显示在类

str 函数中
def __str__(self):
    '''
    returns a string representation of a CarpetSea, i.e. display the organized contents of each cell. 
    Rows and columns should be labeled with indices.

    Example (see "Example Run" in the PA8 specs for more):
      0  1  
    --------
    0|M |  |
    --------
    1|  |* |
    --------

    Note: call Cell's __str__() to get a string representation of each Cell in grid
    i.e. "M " for Cell at (0,0) in the example above
    '''
    return 

以下是我创建网格的一些代码

def __init__(self, N):
    '''

    '''
    self.N = N
    self.grid = []
    for i in range(self.N):
        row = []
        for j in range(self.N):
            cell = Cell(i, j)
            row.append(cell)
        self.grid.append(row)


    self.available_fish = ["Salmon", "Marlin", "Tuna", "Halibut"]

这是我更新的 str 函数,但它会出现序列错误

def __str__(self):
    '''
    returns a string representation of a CarpetSea, i.e. display the organized contents of each cell. 
    Rows and columns should be labeled with indices.

    Example (see "Example Run" in the PA8 specs for more):
      0  1  
    --------
    0|M |  |
    --------
    1|  |* |
    --------

    Note: call Cell's __str__() to get a string representation of each Cell in grid
    i.e. "M " for Cell at (0,0) in the example above
    '''        
    self.grid.append("1     0")
    for _ in range(self.N):
        self.grid.append("-" * 8)

    return "\n".join(self.grid)

1 个答案:

答案 0 :(得分:1)

列出一行。加入他们的新行。

class Grid:
  def __init__(self, w, h):
    self.w = w
    self.h = h

  def __str__(self):
    lines = []
    lines.append("header")
    for _ in range(self.h):
        lines.append('-' * self.w)

    return "\n".join(lines)

g = Grid(4, 5)
print(g)

输出

header
----
----
----
----
----

换句话说,print应为lines.append()。这是一个练习,让你弄清楚如何处理end=''的转换。