在写一个小游戏作业的过程中,我遇到了这样的问题:
我定义了类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)