简体   繁体   中英

How to access a child class method from a parent class?

There are a lot of answers saying this is unadvisable, but I found a scenario where I think it's useful. Please correct me if I'm wrong and there's a better way.

I'm building a chess game, where individual pieces inherit from the superclass Chesspiece :

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

Each piece has a method that defines the moves it can take:

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

I'd like to implement a move() function. The code for the move() function will be the same for each piece, except for the fact that it has to compare the suggested move with the possible moves, which vary for each piece. I could make a move() function for each piece, but that would just be repeating code 6 times.

So, I'd like to define move() in Chesspiece and reference each piece's possible_moves() function.

It is simpler to implement an empty possible_moves in the parent:

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

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

Or even return an empty set of movements in the parent class:

def possible_moves(self):
    return set()

But I think the first is better, so it forces all subclasses to implement it in order to been useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM