【问题标题】:Inherit from collections.Counter: 'fromkeys' is abstract从 collections.Counter 继承:'fromkeys' 是抽象的
【发布时间】:2017-06-14 12:27:21
【问题描述】:

我有一个继承自 collections.Counter 的 python 类:

class Analyzer(collections.Counter):
   pass

当我在这段代码上使用 pylint 时,它的答案是:

W:方法“fromkeys”在“Counter”类中是抽象的,但未被覆盖(抽象方法)

我在我的机器上检查了collections.Counter 的实现,实际上,这个方法没有实现(评论有助于理解原因):

class Counter(dict):
    ...
    @classmethod
    def fromkeys(cls, iterable, v=None):
        # There is no equivalent method for counters because setting v=1
        # means that no element can have a count greater than one.
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

但是,我真的不知道如何实现这个方法,如果Counter 本身没有......

在这种情况下如何解决这个警告?

【问题讨论】:

  • 忽略警告?皮林特错了,曲解了事情。
  • 我的意思是,一个天真的解决方案可能是以collections.Counter 中的方式实现它。但这甚至不应该是必要的......
  • 这是警告而不是错误
  • @MartijnPieters 这就是我到现在为止的处理方式......
  • @JaredGoguen 或者,不要重新实现它,而是重用泄漏的实现:fromkeys = collections.Counter.fromkeys。但正如你所说,这甚至没有必要。

标签: python inheritance abstract python-collections


【解决方案1】:

This question 应该在这里回答一些问题。基本上,pylint 检查引发的NotImplementedError 异常以确定方法是否是抽象的(在这种情况下为误报)。添加评论 #pylint: disable=W0223 将禁用此检查。

this question 中也提出了类似的问题。

【讨论】:

  • 但是,如果 pylint 将 Counter 视为抽象类,因为 fromkeys 引发了 NotImplementedError,它必须认为不正确才能实例化它。不是吗?
【解决方案2】:

有两种不同的思维方式。

  • Counter 视为抽象(正如pylint 所做的那样,正如Jared 所解释的那样)。然后,类Analyzer 必须实现fromkeys 或者也是抽象的。但是,一个人应该无法实例化Counter
  • Counter 视为具体的,即使您不能使用它的fromkeys 方法。然后,必须禁用pylint的警告(因为在这种情况下是错误的,请参阅Jared's answer了解如何),并且Analyzer类也是具体的,不需要实现此方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多