1

I'd like to have an ability to reset an integer/float to the predefined default value without overriding all arithmetic operations. Something like

class DefaultInt(int):

def __init__(self, value):
    super(DefaultInt, self).__init__(value)
    self.default_value = value

def reset(self):
    self.value = self.default_value

my_int = DefaultInt(19)
my_int += 1
my_int.reset()

But there are two problems:

  • I cannot access the hidden value itself by subclassing int class.
  • After my_int += 1 the my_int becomes, obviously, a simple int.
dizcza
  • 630
  • 1
  • 7
  • 19

2 Answers2

0

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).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
-1

I think that, if you only need a reset function, you can simply use:

default_value = 5
my_int = int.__new__(int, default_value)
my_int += 1
print my_int   #  prints 6
my_int = int.__new__(int, default_value)
print my_int   # prints 5
Zionsof
  • 1,196
  • 11
  • 23