【问题标题】:PyCharm: Why does signature not match in this case?PyCharm:为什么在这种情况下签名不匹配?
【发布时间】:2020-01-29 16:01:28
【问题描述】:

考虑以下代码示例:

class BaseExtractor(object, metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def extract(self, interval, *args, **kwargs):
        raise NotImplementedError

class ChildExtractor(BaseExtractor):

    def extract(self, interval, variants, anchor, fixed_len=True, **kwargs):
        pass

为什么 PyCharm 告诉我 ChildExtractor.extract()BaseExtractor.extract() 不匹配?

我开始认为我只是犯了一些非常愚蠢的错误......

编辑:

class ChildExtractor(BaseExtractor):

    def extract(self, interval, variants, anchor, *args, fixed_len=True, **kwargs):
        pass

这会导致同样的错误。

【问题讨论】:

  • 大概是因为 Base extract() 接受任意数量的位置参数,但 Child extract() 中没有 *args。
  • 尝试将 *args 添加到 ChildExtractor 的提取方法中。
  • 感谢您的提示。不幸的是,这仍然给出了同样的错误。

标签: python python-3.x pycharm


【解决方案1】:

考虑BaseExtractor的以下用法:

def extractor_usage(extractor: BaseExtractor):
    extractor.extract(interval=10)

它正确使用了BaseExtractor 接口,但将ChildExtractor 传递给此方法会导致TypeError

可以通过将variantsanchor 设为可选来解决此问题,例如:

class ChildExtractor(BaseExtractor):

    def extract(self, interval, variants=None, anchor=None, *args, fixed_len=True, **kwargs):
        pass

extractor_usage(ChildExtractor())  # No TypeError here

【讨论】:

  • 啊,这很有道理!谢谢你的回答。
  • 也就是说,子类方法不允许有额外的必需参数(任何额外的参数必须是可选的或有默认值)。
猜你喜欢
  • 2017-06-11
  • 2020-07-28
  • 2017-01-07
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2016-06-04
相关资源
最近更新 更多