列表未在类中更新(python 3)

时间:2018-01-27 21:32:06

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

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)

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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功能。现在应该可以了。