【问题标题】:list not updating in class (python 3)列表未在类中更新(python 3)
【发布时间】:2018-07-06 22:33:36
【问题描述】:

self.cell 没有更新..

当我在cell_in 中输入值时,update_cell 方法不会列出单元格。 并返回['-','-','-','-','-','-','-','-','-']

class board():
    def __init__(self):
        self.cell=['-','-','-','-','-','-','-','-','-']

    def display(self):
        x=0
        c= self.cell
        for i in range(0,3):
            for j in range(0,3):
                if(j is 0):
                    print(' ',end='')
                print(c[x],end='')
                x+=1
                if(j<2):
                    print(' | ',end='')
            if(i<2):
                print('\n-----------')
        print()



    def update_cell(self,cell_in,player):
        self.cell[(cell_in-1)]= player
def header():
    print("-TicTacToe-")

def ref_scr():
    cls()
    header()
    board().display()
while True:
    ref_scr()
    cell_in = int(input("enter cell between 1 and 9: "))
    player= 'X'
    board().update_cell(cell_in,player)

【问题讨论】:

  • board() 创建一个新的 board 实例,board().update_cell(cell_in,player) 创建一个新实例,更新它,然后将其丢弃。

标签: python python-3.x list class oop


【解决方案1】:

board() 每次都会创建一个新的板子实例。用brd = board()创建一个board实例,并用它来调用brd.update_cell()brd.display()

【讨论】:

    【解决方案2】:

    它应该是这样的。这会阻止代码在每个循环中初始化一个新的板对象。

    def ref_scr(brd):
        cls()  # Not sure what this is. It doesn't appear anywhere else.
        header()
        brd.display()
    
    if __name__ == "__main__":
        brd = Board()
        while True:
            ref_scr(brd)
            cell_in = int(input("enter cell between 1 and 9: "))
            player = 'X'
            brd.update_cell(cell_in, player)
    

    编辑: 继续并更改了 ref_scr 函数。现在应该可以了。

    【讨论】:

    • @SháhrozTanveer“不起作用”不是很具有描述性。然而,这是对类的正确使用。
    • @Myles Hollowed 列表仍未更新.. 当调用 ref_scr() 时(更新后的 x 插槽变为 '-')
    • 我没有调试你的源代码。我刚刚向您展示了使用该类的正确方法。
    • @SháhrozTanveer 您也没有显示您将代码更改为“仍然不起作用”的内容。我们告诉你它有什么问题,现在应用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    相关资源
    最近更新 更多