【问题标题】:ABC class number from number module来自数字模块的 ABC 班级编号
【发布时间】:2019-06-22 17:44:23
【问题描述】:

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__

这是为什么呢?

【问题讨论】:

    标签: python python-2.7 abc isinstance


    【解决方案1】:

    查看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 中的工作方式而无法实例化,而不是因为有人专门构建它。

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2015-09-11
      • 2011-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多