Your immediate problems:
in-place addition needs you to redefine __iadd__
(in-place addition) to return a DefaultInt
object (better save the default value, else it becomes the new value)
The reset
thing looks not possible as you've written, just because integers are immutable. But you could assign back the result of reset
to the same name. That would work.
class DefaultInt(int):
def __init__(self,value=0):
super(DefaultInt, self).__init__()
self.default_value = value
def __iadd__(self,value):
old_default = self.default_value
r = DefaultInt(value + self)
r.default_value = old_default
return r
def reset(self):
return DefaultInt(self.default_value)
my_int = DefaultInt(19)
my_int += 1
print(my_int)
my_int = my_int.reset()
print(my_int)
output:
20
19
Your long-term problems:
But that's a first step. If you try my_int + 12
you'll see that it returns an int
as well: you'll have to define __add__
. Same goes for __sub__
... and there's the "hidden" value problem, and the immutable problem which prevents you to perform an in-place reset
.
Conclusion:
I think the best approach would be not to inherit int
and create your own, mutable, class with all the special methods crafted for your needs (plus the reset
method that would work now). You won't have the constraints you're having when overriding int
, and your code will be clearer, even if method-exhaustive (at least if a method is missing, you'll notice it, instead of calling a method that doesn't fit).