继承collections.Counter: 'fromkeys' 是抽象的
问题描述:
我有一个从collections.Counter
继承Python类:继承collections.Counter: 'fromkeys' 是抽象的
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
本身不...
什么在这种情况下解决这个警告的方法是什么?
答
This question应该回答这里的一些问题。基本上,pylint会检查NotImplementedError
引发的异常,以确定某个方法是否是抽象的(在这种情况下为误判)。添加注释#pylint: disable=W0223
将禁用此检查。
在this question中也提出了类似的问题。
+0
但是,如果pylint认为'Counter'是抽象类,因为'fromkeys'引发了'NotImplementedError',所以它必须考虑不正确来立即执行它。不是吗? – ryolait
答
有两种不同的思维方式。
- 考虑
Counter
作为摘要(如pylint的,如Jared解释)。然后,类Analyzer
必须实现fromkeys
或也是抽象的。但是,然后,不应该instanciateCounter
。 - 将
Counter
视为具体,即使您不能使用其fromkeys
方法。然后,必须禁用pylint的警告(因为在这种情况下它是错误的,请参阅Jared's answer以知道如何),并且类Analyzer
也是具体的并且不需要实现此方法。
只是忽略警告? Pylint错了,误解了事情。 –
我的意思是,一个天真的解决方案可能是像'collections.Counter'中那样以说出的方式实现它。但这不应该是必要的...... –
这是一个警告不是错误 – e4c5