Python类通过函数向下推变量名

2024-04-26 18:58:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我对类不熟悉,但我正在努力将它们合并到所有采用相同输入的函数的程序中(我假设这样做最有意义……?)。我在下国际象棋,所以看起来很合适

下面我举了一个例子,在这里我试着为一个片段引入有效的动作

class Board:

    def __init__(self, board, r, c):
        self.board = board
        self.r = r
        self.c = c

    def piece(self): 
        return self.board[self.r,self.c]

    def color(self):
        #does this line not get pushed down so 'legal_moves' can't see self.piece?
        self.piece = Board(self.board,self.r,self.c).piece()

        if self.piece == '-':
            return 'N'
        elif self.piece.istitle():
            return 'w'
        else: 
            return 'b'

#This is the function that returns None
     def legal_moves(self):

     moves = {'P':[(1,0)],
                   'p':[(-1,0)],
                   'r':[(1,0),(-1,0),(0,1),(0,-1)],
                   'n':[(2,1),(2,-1),(-2,-1),(-2,1)], 
                   'b':[(1,1),(-1,-1),(-1,1),(1,-1)],  
                   'k':[(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(-1,1),(1,-1)]}

    return moves.get(self.piece)

我的棋盘只是一个标准的8x8象棋棋盘,在初始配置中R-K代表“w”,R-K代表“b”(没有移动)

print(Board(curr,1,2).piece())  #returns P - correct
print(Board(curr,1,2).color())  #returns w - correct
print(Board(curr,1,2).legal_moves()) #returns None - incorrect

谢谢你!另外,我是编程新手,所以如果你有任何风格/效率的意见,请添加他们以及


Tags: selfboardnonegetpiece棋盘returndef
1条回答
网友
1楼 · 发布于 2024-04-26 18:58:34

你在self.piece上调用get,这是你的方法,而不是方法的结果。这个键不在dict中,您得到的默认值是get

您需要:

moves.get(self.piece())

也许使用属性修饰符使piece成为属性会更具可读性(而且您不需要()

@property
def piece(self): 
    return self.board[self.r,self.c]

有了这个moves.get(self.piece)就行了

相关问题 更多 >