我是 Python 新手,我对 builtins 模块中 numbers.Integral 和 int 之间的关系有点困惑。
那么我的问题是:
numbers.Integral和int有什么关系?是不是类似于Java中Integer和int的关系(Integer只是对int的一个包装类)?
什么时候使用 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/