考虑以下代码示例
import abc
class ABCtest(abc.ABC):
@abc.abstractmethod
def foo(self):
raise RuntimeError("Abstract method was called, this should be impossible")
class ABCtest_B(ABCtest):
pass
test = ABCtest_B()
这正确地引发了错误:
Traceback (most recent call last):
File "/.../test.py", line 10, in <module>
test = ABCtest_B()
TypeError: Can't instantiate abstract class ABCtest_B with abstract methods foo
但是,当 的子类ABCtest
也继承自内置类型str
或list
没有错误并test.foo()
调用抽象方法时:
class ABCtest_C(ABCtest, str):
pass
>>> test = ABCtest_C()
>>> test.foo()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
test.foo()
File "/.../test.py", line 5, in foo
raise RuntimeError("Abstract method was called, this should be impossible")
RuntimeError: Abstract method was called, this should be impossible
这似乎在从 C 中定义的任何类继承时发生,包括itertools.chain
但numpy.ndarray
仍然正确地引发了在 python 中定义的类的错误。为什么实现一种内置类型会破坏抽象类的功能?