我正在尝试深入了解Python的数据模型,但我并不完全理解以下代码:
>>> x = 1
>>> isinstance(x,int)
True
>>> isinstance(x,numbers.Integral)
True
>>> inspect.getmro(int)
(<type 'int'>, <type 'object'>)
>>> inspect.getmro(numbers.Integral)
(<class 'numbers.Integral'>, <class 'numbers.Rational'>, <class 'numbers.Real'>,
<class 'numbers.Complex'>, <class 'numbers.Number'>, <type 'object'>)
基于以上所述,似乎int
和number.Integral
不在同一层次结构中。
从Python参考(2.6.6)我看到
numbers.Integral - 这些代表整数数学集合中的元素(正面和负面)。
int
和numbers.Integral
之间有什么区别?它与我在上面的输出中看到的type int
vs class numbers.Integral
有什么关系吗?
答案 0 :(得分:8)
numbers
定义了抽象类的层次结构,用于定义数值类型可能的操作。见PEP 3141。 int
和Integral
之间的区别在于int
是支持Integral
定义的所有操作的具体类型。
答案 1 :(得分:2)
In [34]: numbers.Integral ?
Type: ABCMeta
Base Class: <class 'abc.ABCMeta'>
String Form: <class 'numbers.Integral'>
Namespace: Interactive
File: c:\python26\lib\numbers.py
Docstring:
Integral adds a conversion to long and the bit-string operations.
In [35]: int ?
Type: type
Base Class: <type 'type'>
String Form: <type 'int'>
Namespace: Python builtin
Docstring:
int(x[, base]) -> integer
In [36]: type(int) == type (numbers.Integral)
Out[36]: False
In [39]: issubclass(int, numbers.Integral)
Out[39]: True
Integral是一个抽象基类。 int
是ABCMeta Integral
答案 2 :(得分:2)
请允许我添加两件事:
isinstance(x,numbers.Integral)
还涵盖long
和
isinstance(x, int)
没有。 numbers.Integral
测试将更接近
isinstance(x, (int, long))
Python 2中的(Python 3终止了long
。)
我更喜欢使用numbers.Integral
进行测试,因为如果您来自int
(或long
),则isinstance(y, numbers.Integral)
仍为True
。
答案 3 :(得分:1)
TLDR:int
is registered作为numbers.Integral
的{{3}}。
# numbers.py:380 (CPython 3.8)
Integral.register(int)
numbers.Integral
是必须提供整数的抽象定义。 int
是整数的具体实现。
isinstance
和issubclass
函数不限于继承。例如,他们可以表达virtual subclass,例如collections.abc.Iterable
:
>>> class MyIterable:
... def __iter__(self): ...
...
>>> issubclass(MyIterable, collections.abc.Iterable)
True
实际上,isinstance
和issubclass
都可以是structural type relations。标准库使用它来定义changed for each type支持具体的子类(通过继承)和虚拟子类(通过Abstract Base Classes (ABC))。
虚拟子类通过继承与它的ABC不相关-因此,其方法解析顺序不使用ABC。具体来说,int
不会继承 numbers.Integral
的任何方法。但是,它独立地实现 numbers.Integral
所需的所有方法,从而满足了numbers.Integral
的定义。