I'm trying to get a deeper understanding in Python's data model and I don't fully understand the following code:
>>> 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'>)
Based on the above, it seems that int
and number.Integral
are not in the same hierarchy.
From the Python reference (2.6.6) I see
numbers.Integral - These represent elements from the mathematical set of integers (positive and negative).
What's the difference between int
and numbers.Integral
? Does it have something to do with the type int
vs class numbers.Integral
I see in the above output?
Numeric Types — int , float , complex. There are three distinct numeric types: integers, floating point numbers, and complex numbers.
In Python, integers are zero, positive or negative whole numbers without a fractional part and having unlimited precision, e.g. 0, 100, -10. The followings are valid integer literals in Python. Integers can be binary, octal, and hexadecimal values.
A real number is a value that represents a quantity along a continuous line, which means that it can have fractions in decimal forms. 4.5 , 1.25 , and 0.75 are all real numbers. In computer science, real numbers are represented as floats. To test if a number is float, we can use the isinstance built-in function.
As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.
numbers
defines a hierarchy of abstract classes that define operations possible on numeric types. See PEP 3141. The difference between int
and Integral
is that int
is a concrete type that supports all the operations Integral
defines.
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 is an Abstract Base Class. int
is a subclass of the ABCMeta Integral
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With