python 3.6 : Signature of {method} incompatible with super type {Class}

标签 python python-3.x type-hinting mypy python-typing

在尝试将我的代码更新为符合 PEP-484 时(我使用的是 mypy 0.610),我遇到了以下报告:

$ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6

myfile.py:154: 错误:“交付”的签名与父类(super class)型“MyClass”不兼容

我的类(class):

from abc import abstractmethod

from typing import Any


class MyClass(object):

@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
    raise NotImplementedError

我的文件.py:

class MyImplementation(MyClass):

[...]

    def deliver(self, source_path: str,
                dest_branches: list,
                commit_msg: str = None,
                exclude_files: list = None) -> bool:

        [...]

        return True

我肯定在这里做错了什么,但我不太明白是什么:)

如有任何指点,我们将不胜感激。

最佳答案

@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
    raise NotImplementedError

这个声明并不意味着子类可以给 deliver 他们想要的任何签名。子类 deliver 方法必须准备好接受父类(super class) deliver 方法将接受的任何参数,因此您的子类 deliver 必须准备好接受任意位置或关键字参数:

# omitting annotations
def deliver(self, *args, **kwargs):
    ...

你的子类的 deliver 没有那个签名。


如果所有子类都应该具有您为 MyImplementation 编写的相同 deliver 签名,那么您应该给 MyClass.deliver同样的签名。如果您的子类将有不同的 deliver 签名,也许这个方法真的不应该在父类(super class)中,或者您可能需要重新考虑您的类层次结构,或者给它们相同的签名。

关于 python 3.6 : Signature of {method} incompatible with super type {Class},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003146/

相关文章:

python - 在 pickle/unpickle 几次迭代后搁置引发 EOFError

python - 如何以函数式风格对数据框执行复杂的索引查询

python - 在RelativeLayout中嵌入GridLayout

python - 带有描述符的类型提示

python - isinstance 如何为 List 工作?

python - Django: 'module' 对象没有属性 'index'

python - 使用 holoviews/hvplot 更改图例位置

python - 从对话框操作更改主窗口事件选项卡

python - 对于文本文件中的每个单词,提取周围的 5 个单词

python - 在 Eclipse 中使用 PyDev 进行类型提示