OverflowError:Python int太大而无法转换为C long

Max*_*amy 9 python

我有这门课:

class MetricInt(int):
    """Int wrapper that adds only during the observation window."""
    def __new__(cls, _, initial):
        return int.__new__(cls, initial)

    def __init__(self, sim, initial):
        int.__init__(initial)
        self.sim = sim

    def __add__(self, val):
        if self.sim.in_observe_window():
            self = MetricInt(self.sim, super(MetricInt, self).__add__(int(val)))
        return self
Run Code Online (Sandbox Code Playgroud)

其中基本上覆盖了__add__方法,以便只self.sim.in_observe_window()返回if True.

但是,如果初始值太大,我有OverflowError: Python int too large to convert to C long.

做我正在做的事情并处理大数字的正确方法是什么?

Eev*_*vee 7

你是Python 2.6吗?您可以尝试子类化long.

但总的来说,我强烈建议不要继承Python内置类型; CPython保留跳过对这些类型的特殊方法的调用的权利,例如不会调用__str__它的子类str.你的例子在这里有用,但你可能会要求bug.

请考虑委派,并委派您想要的运算符.(__int__当然,你可能也想要.)

  • 我有Python 2.7的问题,但我需要我的代码兼容Python2和Python3. (4认同)

Max*_*amy 7

我喜欢Eevee关于代理的答案.他没有提供任何代码所以我这样做:

class MetricInt(object):
    """Int wrapper that adds only during the observation window."""
    def __init__(self, sim, initial):
        self.sim = sim
        self.val = int(initial)

    def __add__(self, val):
        if self.sim.in_observe_window():
            self.val += int(val)
        return self

    def __int__(self):
        return self.val

    def __float__(self):
        return float(self.val)
Run Code Online (Sandbox Code Playgroud)

这样,问题就解决了.当我决定对int类型进行子类化时,这是因为int我的代码中已经有一些变量,并且不想过多地更改我的代码.但是,如果我定义__int__并且__float__,我只需要添加一些强制转换int.它不是那么糟糕,我想如果它避免了奇怪的错误.