python - 来自数字模块的 ABC 类数字

标签 python python-2.7 abc isinstance

创建 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.Realnumbers.Complex 继承自 numbers.Number 并用 修饰许多方法@abc.abstractmethod,因此它们不能被实例化。

这意味着 numbers.Number 很可能只是因为抽象类在 Python 中的工作方式而可实例化,而不是因为有人专门将它构建成这样。

关于python - 来自数字模块的 ABC 类数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56717751/

相关文章:

python - 替代 df.iterrows() 用于连接两个 Postgres 表和计算功能

regex - pandas python 中字符串的精确匹配

python - QTableWidget - 改变行颜色

python - python 条件 (if) 语句是否有最大长度?

c++ - 调用虚函数时继承类 "invalid pointer error"

python - 如何在 python 2.7 中为 TLS 套接字进行证书固定?

Python:复制路径中带有特殊字符的文件

python - Pandas 如何过滤多个系列的子串

python - Python 中的抽象方法继承

python - Python中继承的抽象类上的`__subclasshook__`?