2017-10-19 49 views
0

我是新來的類,但試圖努力將它們合併到所有采用相同輸入的函數的程序中(我假設這樣做時,它使得最多感...?)。我正在研究一個棋盤,所以它看起來合適。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 

謝謝!另外,我是編程新手,所以如果您有任何風格/效率評論,請添加它們。

回答

2

你打電話getself.piece這是你的方法,而不是結果的方法。這關鍵是不是在你的字典,你會得到的get

默認值你需要:

moves.get(self.piece()) 

使用屬性裝飾會更可讀的(也許讓piece一個財產,你不會需要()

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

moves.get(self.piece)作品。

+0

非常感謝!完善。作爲一個方面說明,我應該能夠定義'def valid_move(self,r,c,r_offset):self.r_offset,self.c_offset = r + r_offset,c + c_offset',然後使用'self.r_offset'同一班級的其他職能?這似乎不是,但只是想仔細檢查 – user6142489