创建 ABC 类是为了检查对象类型,因此它们不能被实例化。事实上:
basestring()
抛出:
TypeError: The basestring type cannot be instantiated
但是,这不会发生在 ABC 号码上:
from numbers import number
number()
它不会抛出任何异常。而来自同一模块的其他 ABC:
from numbers import Real
from numbers import Complex
Real() # or Complex()
抛出:
TypeError: Can't instantiate abstract class Real with abstract methods __abs__, __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mod__, __mul__, __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__, __rpow__, __rtruediv__, __truediv__, __trunc__
这是为什么?
最佳答案
看看 source for the numbers module提供答案:
class Number(metaclass=ABCMeta): """All numbers inherit from this class. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number). """ __slots__ = () # Concrete numeric types must provide their own hash implementation __hash__ = None
如您所见,numbers.Number
类将 abc.ABCMeta
作为元类。因为它没有用 @ab.cabstractmethod
、@abc.abstractclassmethod
或 @abc.abstractstaticmethod
修饰的方法,所以 abc.ABCMeta
类不会阻止实例化。
另一方面,类 numbers.Real
和 numbers.Complex
继承自 numbers.Number
并用 修饰许多方法@abc.abstractmethod
,因此它们不能被实例化。
这意味着 numbers.Number
很可能只是因为抽象类在 Python 中的工作方式而可实例化,而不是因为有人专门将它构建成这样。
关于python - 来自数字模块的 ABC 类数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56717751/