Can't instantiate abstract class … with abstract methods
我正在开发一种lib,出于一种奇怪的原因,我遇到了这个错误。
- 这是我的代码。 当然@ abc.abstractmethod必须取消注释
- 这是我的测试
抱歉不能只复制并粘贴它
我基于以下代码工作
test.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import abc import six @six.add_metaclass(abc.ABCMeta) class Base(object): @abc.abstractmethod def whatever(self,): raise NotImplementedError class SubClass(Base): def __init__(self,): super(Base, self).__init__() self.whatever() def whatever(self,): print("whatever") |
在python shell中
1 2 3 | >>> from test import * >>> s = SubClass() whatever |
为什么我的名册模块出现此错误
1 | Can't instantiate abstract class Player with abstract methods _Base__json_builder, _Base__xml_builder |
提前致谢
之所以会出现问题,是因为您已经在基本抽象类中定义了抽象方法,并在其前面加上了
函数的名称从
为了在您的示例中显示此行为-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> import abc >>> import six >>> @six.add_metaclass(abc.ABCMeta) ... class Base(object): ... @abc.abstractmethod ... def __whatever(self): ... raise NotImplementedError ... >>> class SubClass(Base): ... def __init__(self): ... super(Base, self).__init__() ... self.__whatever() ... def __whatever(self): ... print("whatever") ... >>> a = SubClass() Traceback (most recent call last): File"<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class SubClass with abstract methods _Base__whatever |
当我将实现更改为以下内容时,它可以工作
1 2 3 4 5 6 7 8 9 | >>> class SubClass(Base): ... def __init__(self): ... super(Base, self).__init__() ... self._Base__whatever() ... def _Base__whatever(self): ... print("whatever") ... >>> a = SubClass() whatever |
但这非常繁琐,您可能需要考虑是否真的要使用