有人知道Python如何管理内部int和long类型?
我应该如何理解下面的代码?
>>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>
更新:
>>> print type(0x7fffffff)
<type 'int'>
>>> print type(0x80000000)
<type 'long'>
答案 0 :(得分:104)
int
和long
是“统一”a few versions back。在此之前,可以通过数学操作溢出一个int。
3.x通过完全消除int并且只有很长时间来进一步推进这一点。
sys.maxint
包含Python int可以容纳的最大值。
sys.getsizeof()
。sys.maxsize
包含Python int可以的最大字节数。
sys.maxsize
的幂相近8。答案 1 :(得分:15)
这PEP应该会有所帮助。
底线是你真的不应该在python版本中担心它&gt; 2.4
答案 2 :(得分:4)
有趣。在我的64位(i7 Ubuntu)框中:
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>
猜测它在更大的机器上可以达到64位整数。
答案 3 :(得分:3)
在我的机器上:
>>> print type(1<<30)
<type 'int'>
>>> print type(1<<31)
<type 'long'>
>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'long'>
Python使用整数(32位有符号整数,我不知道它们是否是引擎盖下的C ints)适用于32位的值,但会自动切换为long(任意大量的位 - 即bignums) )更大的东西。我猜这可以加快速度,同时避免任何溢出,无缝过渡到bignums。
答案 4 :(得分:3)
Python 2.7.9自动提升数字。 对于不确定使用int()或long()的情况。
>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>
答案 5 :(得分:2)
Python 2将根据值的大小自动设置类型。最大值的指南可以在下面找到。
Python 2中默认Int的最大值为65535,任何高于此值的值都将很长
例如:
>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>
在Python 3中,长数据类型已被删除,所有整数值都由Int类处理。 Int的默认大小取决于您的CPU架构。
例如:
每种类型的最小值/最大值可在下面找到:
如果您的Int大小超过上述限制,python将自动更改其类型并分配更多内存以处理此最小值/最大值的增加。在Python 2中,它将转换为“ long”,现在仅转换为下一个Int大小。
示例:如果您使用的是32位操作系统,则默认情况下,Int的最大值为2147483647。如果指定的值为2147483648或更大,则类型将更改为Int64。
有多种方法可以检查int的大小及其内存分配。
注意:在Python 3中,无论您使用的是什么Int大小,使用内置的type()方法将始终返回<class 'int'>
。
答案 6 :(得分:1)
从python 3.x开始,统一整数库比旧版本更加智能。在我的(i7 Ubuntu)框中,我得到了以下内容,
>>> type(math.factorial(30))
<class 'int'>
有关实施细节,请参阅Include/longintrepr.h, Objects/longobject.c and Modules/mathmodule.c
个文件。最后一个文件是动态模块(编译为so文件)。该代码评论很好。
答案 7 :(得分:0)
它管理它们,因为int
和long
是兄弟类定义。他们有适当的+, - ,*,/等方法,可以产生适当类的结果。
例如
>>> a=1<<30
>>> type(a)
<type 'int'>
>>> b=a*2
>>> type(b)
<type 'long'>
在这种情况下,类int
有__mul__
方法(实现*的方法),在需要时会创建long
结果。
答案 8 :(得分:0)
只需继续此处给出的所有答案,尤其是@James Lanes
整数类型的大小可以通过以下公式表示:
总范围=(2 ^位系统)
下限=-(2 ^位系统)* 0.5 上限=((2 ^位系统)* 0.5)-1
答案 9 :(得分:0)