I am a newbie for Python, I am a little confuse of the relationship between numbers.Integral and int in builtins module.
Then my questions are:
-
What the relationship between numbers.Integral and int? Is it similiar with the relationship between Integer and int in Java (Integer is just a wrapper class for int)?
-
When to use numbers.Integral?
Since none of the types defined in mumbers module can be instantiated, then in what kind of scenarios we need to use these types?
Only one case I know we can use Integral:
# check if x is a integer
isinstance(x, Integral)
From the Python language reference:
”
numbers.Number These are created by numeric literals and returned as
results by arithmetic operators and
arithmetic built-in functions. “
But it seems the arithmetic operators or arithmetic built-in functions doesn’t return a type in numbers. It is still the type in builtins.
>>> a,b=123,5
>>> c=a*b
>>> print(c.__class__)
<class 'int'>
>>> d=abs(a)
>>> print(d.__class__)
<class 'int'>
I am using Python 3.2a3.
Since you sound like you know Java:
numbers.Integraldefines the “interface” (it’s really a generalization of interfaces, called “Abstract Base Class” (ABC)) for integral numbers. It’s not a concrete type that you can instantiate.The only builtin type that implements this interface is
int.With
isinstance( obj, numbers.Integral)you can test ifobjimplements a interface:If you wanted to write a custom class that behaves like a integral number you would inherit from
numbers.Integral— or if you wanted to invent a new type of number you could register it there.