簡體   English   中英

如何從父類訪問子類方法?

[英]How to access a child class method from a parent class?

有很多答案說這是不可取的,但我發現了一個我認為它有用的場景。 如果我錯了,請糾正我,還有更好的方法。

我正在構建一個國際象棋游戲,其中單個棋子從超類Chesspiece繼承:

class ChessPiece:
    def __init__(self, pos, color, num, piece):
        ...

每個部分都有一個方法來定義它可以采取的動作:

class Knight(ChessPiece):
    def __init__(self, pos, color=None, num=''):
        ChessPiece.__init__(self, pos, color, num, self.__class__.__name__)


    def possible_moves(self):
        pos_moves = []

        # Up, Right (1 space, 2 spaces)
        try:
            if 1 <= self.x + 2 <= len(Config.board) and 1 <= self.y - 1 <= len(Config.board):
                if Config.board[self.x + 2][self.y - 1] == '___':
                    pos_moves.append(f'{Config.tile_convert(self.x + 2)}{Config.tile_convert(self.y - 1, True)}')

        except Exception: pass

        #Up, Left
        ...

        return pos_moves

我想實現一個move()函數。 move()函數的代碼對於每個棋子都是相同的,除了它必須將建議的移動與可能的移動進行比較,這對於每個棋子都是不同的。 我可以為每個部分創建一個move()函數,但這只會重復代碼 6 次。

所以,我想在Chesspiece定義move()並引用每個棋子的possible_moves()函數。

在父級中實現一個空的possible_moves更簡單:

class ChessPiece:
    ...
    def possible_moves(self):
        raise NotImplementedError

    def move(self, pos):
            if pos in self.possible_moves():
            ...

或者甚至在父類中返回一組空的動作:

def possible_moves(self):
    return set()

但我認為第一個更好,因此它強制所有子類都實現它以便有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM