您可以使用
ctypes.c_longlong:
>>> from ctypes import c_longlong as ll>>> ll(2 ** 63 - 1)c_longlong(9223372036854775807L)>>> ll(2 ** 63)c_longlong(-9223372036854775808L)>>> ll(2 ** 63).value-9223372036854775808L
如果您确实知道目标计算机上的a将是64位宽,那么这实际上 只是 一个选择
signed long long。
编辑: jorendorff为64位数字定义类的想法很吸引人。理想情况下,您要减少显式类创建的数量。
使用
c_longlong,您可以执行以下操作( 注意: 仅适用于Python 3.x!):
from ctypes import c_longlongclass ll(int): def __new__(cls, n): return int.__new__(cls, c_longlong(n).value) def __add__(self, other): return ll(super().__add__(other)) def __radd__(self, other): return ll(other.__add__(self)) def __sub__(self, other): return ll(super().__sub__(other)) def __rsub__(self, other): return ll(other.__sub__(self)) ...
这样,结果
ll(2 ** 63) -1的确是
9223372036854775807。但是,这种构造可能会导致性能下降,因此根据您要精确执行的操作,定义上述类可能不值得。如有疑问,请使用
timeit。



