int() 和 long() 之间的区别

Difference between int() and long()

int(x) and long(x)和python

有什么区别

我的理解:

  1. long() 总是 return 一个 long
  2. int() 将 return 一个 int 或一个 long(如果它太大)
  3. 所以 int() 足以根据其值
  4. 动态获取 int/long

所以除非以上(1)(2)(3)不正确,否则为什么需要long()? int() 何时完成工作? 跳过所有数字范围的 long() 会伤害我吗?


引用的文档:

class 整数(x=0)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, it can be a plain integer, a long integer, or a floating point number. If x is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.

class长(x=0)

Return a long integer object constructed from a string or number x. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The base argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.


代码实验

number = int(number_string) # cast it to integer
print number, "\t", type(number)

number = long(number_string) # cast it to long
print number, "\t", type(number)

int:整数;相当于 Python 2.x 中的 C 长,Python 3.x

中的非限制长度

long:长度不受限制的长整数;仅存在于 Python 2.x

因此,在 python 3.x 及更高版本中,您可以使用 int() 而不是 long().