I have this class:
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
Which basically overwrite the __add__ method in order to only to the addition if self.sim.in_observe_window() returns True.
However, if the initial value is too big, I have :
OverflowError: Python int too large to convert to C long.
What is the correct way to do what I'm trying to do and also handle big numbers?
Are you on Python 2.6? You could try subclassing long instead.
But in general I strongly suggest not subclassing Python built-in types; CPython reserves the right to skip calls to special methods on such types, and for example will not call __str__ on a subclass of str. Your example here works, but you might be asking for bugs.
Consider delegating instead, and delegating the operators you want. (You may also want __int__, of course.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With