具体subclass的实例是抽象class的实例吗?

Is an instance of a concrete subclass an instance of the abstract class?

根据定义,我们不能实例化一个抽象class:

>>> import abc
>>> class A(abc.ABC):
...     @abc.abstractmethod
...     def f(self): raise NotImplementedError
... 
>>> A()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class A with abstract method f

那么,具体子class的实例是抽象class的实例,这不是自相矛盾吗?

>>> class B(A):
...     def f(self): return 'foo'
... 
>>> isinstance(B(), A)
True

一个对象一个class的一个实例和实例化一个[=35]的行为是有区别的=].继承意味着如果 BA 的子 class,则 isinstance(B(), A) 为真,即使 B 而不是 A 是class 正在实例化。

如果您永远无法具体化抽象 class,那么首先定义抽象 class 就毫无意义。摘要 class 的目的是为其他 class 提供一个不完整的模板;你不能简单地按原样使用抽象 class 而不做一些额外的定义。

换句话说,给定 b = B()bAB 实例 ,但只有 Bb 类型 。 Is-type-of 和 is-instance-of 是两种不同的关系。