次のコード例を検討してください
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 で定義されたクラスでエラーが正しく発生します。組み込み型の 1 つを実装すると、抽象クラスの機能が損なわれるのはなぜですか?