python - Python 3 内置模块中 numbers.Integral 和 int 之间的关系是什么

标签 python python-3.x

我是 Python 新手,我对 builtins 模块中 numbers.Integral 和 int 之间的关系有点困惑。

那么我的问题是:

  1. numbers.Integral和int有什么关系?是不是类似于Java中Integer和int的关系(Integer只是对int的一个包装类)?

  2. 什么时候使用 numbers.Integral? 既然mumbers模块中定义的类型都不能被实例化,那么在什么样的场景下我们需要使用这些类型呢?

我知道只有一种情况可以使用 Integral:

 # check if x is a integer
 isinstance(x, Integral)

来自Python语言引用:

" numbers.Number These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. "

但算术运算符或算术内置函数似乎不返回数字类型。它仍然是内置的类型。

>>> a,b=123,5
>>> c=a*b
>>> print(c.__class__)
<class 'int'>
>>> d=abs(a)
>>> print(d.__class__)
<class 'int'>

我正在使用 Python 3.2a3。

最佳答案

既然您听起来像您了解 Java:numbers.Integral 为整数定义了“接口(interface)”(它实际上是接口(interface)的概括,称为“抽象基类”(ABC))。它不是您可以实例化的具体类型。

实现此接口(interface)的唯一内置类型是 int

使用 isinstance( obj, numbers.Integral) 你可以测试 obj 是否实现了一个接口(interface):

>>> isinstance(3, numbers.Integral)
True
>>> isinstance(3.0, numbers.Integral)
False
>>> isinstance(3+0j, numbers.Integral)
False

如果您想编写一个行为类似于整数的自定义类,您将从 numbers.Integral 继承——或者如果您想发明一种新类型的数字,您可以在那里注册它。

关于python - Python 3 内置模块中 numbers.Integral 和 int 之间的关系是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4281955/

相关文章:

python - 无法从云函数正确访问GCS对象

python - 如何使用内容编码 : gzip with Python SimpleHTTPServer

python - jsonify flask-sqlalchemy flask中的多对一关系

mysql - Lambda (Python 3.6) PyMySql 查询 EXISTS 查询总是返回 1

python - 使用 PyMySQL 建立与服务器的连接时遇到问题 [WinError 10054]

python-3.x - 递归地展平列表列表

python - ncurses 和白底黑字

python-3.x - Python pkg_resources 和包中的文件访问

python - 如何在应用函数上连接 sum 并将数据帧打印为文件中的表格格式

python - 实现极小极大算法时的递归问题