为什么这个函数返回long而不是int?

时间:2014-08-11 16:01:48

标签: python types int long-integer return-type

我已经定义了一个函数,它将一个正整数作为输入,并返回其数字的总和:

def digitSum(n):
    exp = 0
    digitSum = 0
    while n%(10**exp) != n:
        digitSum += (n%(10**(exp+1))-n%(10**(exp)))/(10**exp)
        exp += 1
    return digitSum

似乎n< 10 ** 9,然后digitSum返回一个int,否则返回一个long。如果我希望它总是返回一个int,我可以让它返回int(digitSum)而不是digitSum,所以这不是问题。我的问题是为什么这首先归来的很长?

2 个答案:

答案 0 :(得分:4)

如果数字太大,

Python< 3会自动将int转换为long。 你可以在这里读更多关于它的内容。

How does Python manage int and long?

(这种自动转换是python消耗更多内存并且比C / C ++更慢的原因之一,但这是另一种讨论)

>>> import sys
>>> x = sys.maxint             # set a variable to your systems maximum integer
>>> print type(x)
<type 'int'>                   # type is then set to int
>>> x += 1                     # if you increase it, it gets converted into long
>>> print type(x)
<type 'long'>

答案 1 :(得分:0)

Python 2区分可以存储在机器的基础int类型(int)中的整数和以该语言实现的任意精度整数(long )。您无法强制函数返回int(无论如何都不会引入溢出错误),因为当值太大而无法容纳long时,Python 2会自动创建int对象。 1}}。

在Python 3中,从Python级别删除了区别:所有值都是int s,无论大小如何,任何更精细的区别都是内置int类型的实现细节。