-1

I've inherited a class from int and I'm trying to create a method that increases my instance's value inside the method:

class MyInt(int):
    def my_method(self, value):
        #do_stuff()
        self += value

I know you can't set self to anything else inside a method, it will sure change inside the method but the actual instance wont change. However, I don't know how can I fix this so that the actual instance would change, so is it even possible? If yes, then how?

Skamah One
  • 2,456
  • 6
  • 21
  • 31
  • 2
    You're trying to mutate an immutable object? – Snakes and Coffee May 12 '13 at 18:41
  • @snakesandcoffee Rather find a workaround to implement behavior similar to mutatable object... – Skamah One May 12 '13 at 18:44
  • You should probably look at this http://stackoverflow.com/questions/33534/extending-base-classes-in-python – Alexander Kuzmin May 12 '13 at 19:05
  • "I've inherited a class from `int` and..." No! Don't do that! Subclassing built-in is the wrong way of doing things most of the times. They **will** bite you in the future(and they already started as you can see). Subclassing a built-in is a great power, but with great power comes great responsibility!!! (BTW: AFAIK you can't do what you are trying to do from python. If there is a way it will surely be nasty...) – Bakuriu May 12 '13 at 19:34

1 Answers1

0

It seems like the best thing to do would be to have MyInt not inherit from int, but rather store an int in an instance variable. So you would have a getValue() method and a setValue() method.

class MyInt()
    def __init__(self, value):
        self.value = value
    def getValue(self):
        return self.value
    def setValue(self, value):
        self.value = value
Eli Rose
  • 6,788
  • 8
  • 35
  • 55