我正在修改text adventure game tutorial,github,以適應python 2.7。我爲我的IDE使用了PyCharm 4.5.4社區版。當我不重寫父方法,它給了我一個錯誤:我必須在python 2.7中實現所有的抽象方法嗎?
Class WolfRoom must implement all abstract methods
首先擺脫這種錯誤,我定義缺少方法def modify_player(self, the_player):
爲pass
,但我很快就意識到我被覆蓋方法與它無關不是我想要的。現在,如果我只是從WolfRoom類中移除該方法,則會出現IDE錯誤,如上所示,但在運行我的遊戲時似乎工作得很好。我應該離開這個方法還是定義它並使用super()
?
下面是一些代碼片段:
class MapTile(object):
"""The base class for all Map Tiles"""
def __init__(self, x, y):
"""Creates a new tile.
Attributes:
:param x: The x coordinate of the tile.
:param y: The y coordinate of the tile.
"""
self.x = x
self.y = y
def intro_text(self):
"""Information to be displayed when the player moves into this tile."""
raise NotImplementedError()
def modify_player(self, the_player):
"""Process actions that change the state of the player."""
raise NotImplementedError()
def adjacent_moves(self):
"""Returns all move actions for adjacent tiles."""
moves = []
if world.tile_exists(self.x + 1, self.y):
moves.append(actions.MoveEast())
if world.tile_exists(self.x - 1, self.y):
moves.append(actions.MoveWest())
if world.tile_exists(self.x, self.y - 1):
moves.append(actions.MoveNorth())
if world.tile_exists(self.x, self.y + 1):
moves.append(actions.MoveSouth())
return moves
def available_actions(self):
"""Returns all of the available actions in this room"""
moves = self.adjacent_moves()
moves.append(actions.ViewInventory())
return moves
...
class EnemyRoom(MapTile):
def __init__(self, x, y, enemy):
self.enemy = enemy
super(EnemyRoom, self).__init__(x, y)
def intro_text(self):
pass
def modify_player(self, the_player):
if self.enemy.is_alive():
the_player.hp = the_player.hp - self.enemy.damage
print("Enemy does {} damage. You have {} HP remaining.".format(self.enemy.damage, the_player.hp))
def available_actions(self):
if self.enemy.is_alive():
return [actions.Flee(tile=self), actions.Attack(enemy=self.enemy)]
else:
return self.adjacent_moves()
...
class WolfRoom(EnemyRoom):
def __init__(self, x, y):
super(WolfRoom, self).__init__(x, y, enemies.Wolf())
def intro_text(self):
if self.enemy.is_alive():
return """
A grey wolf blocks your path. His lips curl to expose canines as white as
the nights sky. He crouches and prepares to lunge.
"""
else:
return"""
The corpse of a grey wolf lays rotting on the ground.
"""
Python實際上並沒有「抽象」的概念......除非你使用的庫強制執行方法通過提出錯誤或其他東西來覆蓋。 – zstewart
@zstewart Python確實具有抽象類和方法,如果您嘗試在不覆蓋所有抽象方法的情況下實例化子類,那麼這些抽象類和方法將通過錯誤實施。 –
@SnakesandCoffee *如果您使用'ABCMeta'元類,它屬於zstewart提及的「正在使用的庫」。語言本身沒有抽象類的概念。 – chepner