Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 编号模块中的ABC类编号_Python_Python 2.7_Abc_Isinstance - Fatal编程技术网

Python 编号模块中的ABC类编号

Python 编号模块中的ABC类编号,python,python-2.7,abc,isinstance,Python,Python 2.7,Abc,Isinstance,创建ABC类是为了检查对象类型,因此不能实例化它们。事实上: basestring() 抛出: TypeError: The basestring type cannot be instantiated TypeError: Can't instantiate abstract class Real with abstract methods __abs__, __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__,

创建ABC类是为了检查对象类型,因此不能实例化它们。事实上:

basestring()
抛出:

TypeError: The basestring type cannot be instantiated
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__
但是,ABC编号不会发生这种情况:

from numbers import number

number()
它不会抛出任何异常。而来自同一模块的其他ABC:

from numbers import Real
from numbers import Complex

Real()  # or Complex()
抛出:

TypeError: The basestring type cannot be instantiated
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__
这是为什么呢?

看一下下面的答案:

如您所见,
numbers.Number
类将
abc.ABCMeta
作为元类。由于它没有用
@ab.cabstractmethod
@abc.abstractclassmethod
@abc.abstractstaticmethod
修饰的方法,
abc.ABCMeta
类不会阻止实例化

另一方面,类
numbers.Real
numbers.Complex
继承自
numbers.Number
,并用
@abc.abstractmethod
装饰许多方法,因此它们不能实例化

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