qq_39655563 2021-04-21 17:02 采纳率: 50%
浏览 52

Python 子类调用父类的方法,返回另一个父类的实例后,无法调用另一子类的方法

在写一个小游戏作业的过程中,我遇到了这样的问题:

我定义了类Game,Player,AdvancedGame,HoldingPlayer。其中AdvanceGame继承自Game,HoldingPlayer继承自Player(中间还有一层)。

Game中有get_player()方法,返回一个Player的对象,HoldingPlayer相比Player多了一个get_inventory()方法。

情况是这样:在AdvancedGame中调用get_player()后,用它的返回值(即一个Player)去调用它的get_inventory()方法,在pycharm中出现警告:Cannot find reference 'get_inventory' in 'Player | None' ,并且没有了相关的代码提示功能。

为什么要做上面的事情呢,因为这是在做游戏版本的升级,原来的Game和Player完成的游戏现在由AdvanceGame和HoldingPlayer完成。升级后游戏中不再存在非HoldingPlayer的Player对象。但是好像没有办法解决这个类型提示的问题。

我再这个作业的其他地方也出现了类似的问题,忽略警告后不影响正常的执行。

部分代码如下:

class Player(Entity):
    """
    A player is a subclass of the entity class that represents the player 
    that the user controls on the game grid.
    """

    def display(self) -> str:
        """
        Return the character used to represent the player entity in a text-based
        grid.
        """
        return PLAYER


class Game:
    """
    The Game handles some of the logic for controlling the action of the
    player within the grid.

    The Game class stores an instance of the Grid and keeps track of the player
    within the grid so that the player can be controlled.
    """

    def __init__(self, grid: Grid):
        """
        The construction of a Game instance takes the grid upon which the game
        is being played.

        Preconditions:
            The grid has a player, i.e. grid.find_player() is not None.

        Parameters:
            grid: The game's grid.
        """
        self._grid = grid
        self._steps_count = 0


    def get_player(self) -> Optional[Player]:
        """
        Return the instance of the Player class in the grid.

        If there is no player in the grid, return None.

        If there are multiple players in the grid, return one of them.
        """
        if self._grid.find_player() is not None:
            return self._grid.get_entity(self._grid.find_player())

    

class HoldingPlayer(VulnerablePlayer):
    """
    A subclass of VulnerablePlayer that extends the existing
    functionality of the player.

    A Holding player will now keep an inventory.
    """

    def __init__(self):
        super().__init__()
        self._inventory=Inventory()

    def get_inventory(self) -> Inventory:
        """
        Return the instance of the Inventory class that represents the
        player's inventory.
        """
        return self._inventory

AdvancedGame(IntermediateGame):
    """
    The AdvancedGame class extends IntermediateGame to add support for
    the player picking up a Pickup item when they come into contact
    with it.
    """

    def move_player(self, offset: Position) -> None:
        """
        Move the player entity in the grid by a given offset.

        If the player moves onto a Pickup item, it should be added to
        the player’s inventory and removed from the grid.

        Parameters:
            offset: A position to add to the player’s current position to produce the player’s new desired position.
        """
        target_position=self._grid.find_player().add(offset)
        if self.get_grid().get_mapping()[target_position].display() \
            in PICKUP_ITEMS:
            self.get_player().get_inventory() # 这里有问题
        self._grid.move_entity(self._grid.find_player(),
                               target_position)
  • 写回答

1条回答 默认 最新

  • 天元浪子 Python领域优质创作者 2021-04-22 09:02
    关注

    Game.find_player(),其实是Game.grid.find_player(),Game.grid来自Game实例化时传入的类Grid的实例。问题的关键在于,Grid.find_player()返回的是Player对象而非HoldingPlayer对象,而get_inventory()只属于HoldingPlayer,和Player没有半毛钱关系。题主试图从Game的派生类AdvanceGame的实例中调用Player.get_inventory(),岂不是缘木求鱼?

    简单总结为一句话:哪吒(HoldingPlayer)是李靖(Player)的派生类,哪吒有三头六臂(get_inventory()),不代表李靖(Player)也有三头六臂(get_inventory())。

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题