我是否必须在 python 2.7 中实现所有抽象方法?
Do I have to implement all abstract methods in python 2.7?
我正在调整 text adventure game tutorial, github,以适应 python 2.7。我正在为我的 IDE 使用 PyCharm 4.5.4 社区版。当我不覆盖父方法时,它会给我一个错误:
Class WolfRoom must implement all abstract methods
起初为了消除这个错误,我将缺少的方法 def modify_player(self, the_player):
定义为 pass
,但我很快意识到我正在重写该方法,这不是我想要的。现在,如果我只是从 WolfRoom class 中删除该方法,我会收到一个 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.
"""
简单地从一个方法中引发 NotImplementedError
并不 完全 使它成为一个抽象方法。您仍然可以实例化一个 class 不覆盖其所有继承的伪抽象方法,您只是不能 调用 方法。 (或者更确切地说,如果您在 try
语句中捕获 NotImplementedError
,您甚至可以调用它们。)
您可以使用abc.ABCMeta
来使class真正抽象; metaclass 机制甚至会阻止您使用未覆盖的抽象方法实例化 class。
import abc
class MapTile(object):
"""The base class for all Map Tiles"""
__metadata__ = abc.ABCMeta
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
@abc.abstractmethod
def intro_text(self):
"""Information to be displayed when the player moves into this tile."""
pass
# etc.
是的,您必须实现 Python 中的所有抽象方法才能将它们实例化为对象(标有 @abstractmethod
的对象,等等)。但是,如何实现这些完全取决于您。如果您不打算实例化,则不需要覆盖所有这些。
例如:
class Animal(object):
__metaclass__ = ABCMeta
@abstractmethod
def eat(thing):
pass
class Slug(Animal):
def eat(thing):
pass
这意味着每个可实例化的Animal
必须能够进食,但是Slugs
它们进食时什么都不做。
我认为这实际上是由于 PyCharm 检查员在查看是否有任何未实现的方法时犯了错误,或者至少是关于 PEP 8 风格的可疑决定未实现错误。考虑这个非常相似的简单示例:
class Base(object):
def foo(self):
raise NotImplementedError
def bar(self):
return 0
class Child(Base):
def foo(self):
return 0
class GrandChild(Child):
def bar(self):
return 1
my_grand_child = GrandChild()
print my_grand_child.foo()
上面的代码成功地向输出打印了一个 0,因为当 Python 在 GrandChild 中找不到 foo() 的实现时,它会查找继承链并在 Child 中找到它。然而,出于某种原因,PyCharm 检查员期望所有引发 NotImplementedError 的 classes 在继承链的所有级别中实现。
如果您在具有大型继承结构的程序中遵循这种风格,您会发现自己在实现方法和在整个链中调用 super 时非常冗长,而实际上根本不需要这样做。就个人而言,我只是忽略了这个错误,并且认为 PyCharm 应该更新为不显示它,如果它发现在它正在检查的 class 的任何 superclass 中实现的方法。
我正在调整 text adventure game tutorial, github,以适应 python 2.7。我正在为我的 IDE 使用 PyCharm 4.5.4 社区版。当我不覆盖父方法时,它会给我一个错误:
Class WolfRoom must implement all abstract methods
起初为了消除这个错误,我将缺少的方法 def modify_player(self, the_player):
定义为 pass
,但我很快意识到我正在重写该方法,这不是我想要的。现在,如果我只是从 WolfRoom class 中删除该方法,我会收到一个 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.
"""
简单地从一个方法中引发 NotImplementedError
并不 完全 使它成为一个抽象方法。您仍然可以实例化一个 class 不覆盖其所有继承的伪抽象方法,您只是不能 调用 方法。 (或者更确切地说,如果您在 try
语句中捕获 NotImplementedError
,您甚至可以调用它们。)
您可以使用abc.ABCMeta
来使class真正抽象; metaclass 机制甚至会阻止您使用未覆盖的抽象方法实例化 class。
import abc
class MapTile(object):
"""The base class for all Map Tiles"""
__metadata__ = abc.ABCMeta
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
@abc.abstractmethod
def intro_text(self):
"""Information to be displayed when the player moves into this tile."""
pass
# etc.
是的,您必须实现 Python 中的所有抽象方法才能将它们实例化为对象(标有 @abstractmethod
的对象,等等)。但是,如何实现这些完全取决于您。如果您不打算实例化,则不需要覆盖所有这些。
例如:
class Animal(object):
__metaclass__ = ABCMeta
@abstractmethod
def eat(thing):
pass
class Slug(Animal):
def eat(thing):
pass
这意味着每个可实例化的Animal
必须能够进食,但是Slugs
它们进食时什么都不做。
我认为这实际上是由于 PyCharm 检查员在查看是否有任何未实现的方法时犯了错误,或者至少是关于 PEP 8 风格的可疑决定未实现错误。考虑这个非常相似的简单示例:
class Base(object):
def foo(self):
raise NotImplementedError
def bar(self):
return 0
class Child(Base):
def foo(self):
return 0
class GrandChild(Child):
def bar(self):
return 1
my_grand_child = GrandChild()
print my_grand_child.foo()
上面的代码成功地向输出打印了一个 0,因为当 Python 在 GrandChild 中找不到 foo() 的实现时,它会查找继承链并在 Child 中找到它。然而,出于某种原因,PyCharm 检查员期望所有引发 NotImplementedError 的 classes 在继承链的所有级别中实现。
如果您在具有大型继承结构的程序中遵循这种风格,您会发现自己在实现方法和在整个链中调用 super 时非常冗长,而实际上根本不需要这样做。就个人而言,我只是忽略了这个错误,并且认为 PyCharm 应该更新为不显示它,如果它发现在它正在检查的 class 的任何 superclass 中实现的方法。