python - 如何在子类中接受附加参数? (没有 pylint 的参数 - 不同)

标签 python python-3.x pylint

我有一个代表游戏状态的基类,并提供一个 perform_move 方法:

class GameState:
  # other code
  def perform_move(self, position: LinePosition) -> MoveResult:
    # more code

现在我想创建一个 GameState 的子类来跟踪玩家的得分。 因为基类不关心玩家(关注点分离),所以我需要一个额外的参数来识别正在执行移动的玩家。 我尝试了以下方法:

class ScoreKeepingGameState(GameState):
  # other code
  def perform_move(self, position: LinePosition, *, player_identification: Optional[int] = None) -> MoveResult:
    # more code

我预计这会起作用,因为我可以在没有 player_identification 的情况下调用 ScoreKeepingGameStateperform_move ,唉 pylint 提示道:

W0221: Parameters differ from overridden 'perform_move' method (arguments-differ)

是否有比在 ScoreKeepingGameStateperform_move 定义中添加 # pylint:disable=arguments-differ 更简洁的方法来满足 pylint 的要求?

最佳答案

有一些快速而直接的方法,还有一种重新思考继承的设计和使用的方法。

快速方法:使基类中的perform_move接受*args**kwargs参数;那么继承类也只接受 *args 和 **kwargs ,这一切都会起作用。我不太喜欢它,因为这样我们就失去了函数签名,但它会让 pylint 停止提示。

更长远的方法:如果 GameState 不应该关心玩家分数,那么我认为它还有其他一些单一职责。 GameState 的子类仍然具有相同的责任;他们只是以不同的方式实现它。但现在您还让它负责计算和跟踪玩家的分数。至少我认为这就是 perform_move 的重写版本应该做的事情。

因此,也许您需要一个单独的类 ScoreKeeper 来跟踪分数,并且它不应该继承自 GameState

然后你会有一个类负责“处理”玩家的 Action 。该类将分别与 GameState 通信,告诉它有关线的位置,并与 ScoreKeeper 通信,告诉它有关玩家的信息。

关于python - 如何在子类中接受附加参数? (没有 pylint 的参数 - 不同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760572/

相关文章:

python - PyInstaller 使用 pip 安装了 'successfully' 但找不到 pyinstaller.py

python - 如何跳转/显示错误的列

python - 从文档字符串生成 DITA xml

python - 尝试在循环下打印多个变量

gtk 的 python 语言环境在 Windows 上不起作用

python - cv2.HoughCircles 中的图像加载问题

python - Pylint 未分组导入警告

python - 从错误消息中获取禁用 pylint 的错误代码

python - Python 是如何调用 in-imported 模块的?

python - 用于Python编码的Qt Creator,如何在新运行时清除旧应用程序输出?