Subclassing int in Python
int
is immutable so you can't modify it after it is created, use __new__
instead
class TestClass(int):
def __new__(cls, *args, **kwargs):
return super(TestClass, cls).__new__(cls, 5)
print TestClass()
Though correct the current answers are potentially not complete.
e.g.
a = TestClass()
b = a - 5
print type(b)
Would show b as an integer, where you might want it to be a TestClass.
Here is an improved answer
class positive(int):
def __new__(cls, value, *args, **kwargs):
if value < 0:
raise ValueError("positive types must not be less than zero")
return super(cls, cls).__new__(cls, value)
def __add__(self, other):
res = super(positive, self).__add__(other)
return self.__class__(max(res, 0))
def __sub__(self, other):
res = super(positive, self).__sub__(other)
return self.__class__(max(res, 0))
def __mul__(self, other):
res = super(positive, self).__mul__(other)
return self.__class__(max(res, 0))
def __div__(self, other):
res = super(positive, self).__div__(other)
return self.__class__(max(res, 0))
def __str__(self):
return "%d" % int(self)
def __repr__(self):
return "positive(%d)" % int(self)
Now the same sort of test
>>> a = positive(10)
>>> b = a - 9
>>> print(type(b))
<class '__main__.positive'>
UPDATE:
Added repr and str examples so that the new class prints itself properly. Also changed to Python 3 syntax, even though OP used Python 2, to maintain relevancy.