If you create the class using class Integer(object) Python 3 (I don't know for Python 2) will not allow you to use your custom integer to access list items, for example. So, class Integer(int) should be used in order to Python allows you to use the custom variable for the same things the standard int is used.
Based on juanchopanza's answer, a modification is made to create a custom class inherited from int by using the __new__ method instead of the __init__ method. It's usefull if you want to pass more arguments than just val during the class instantiation.
class Integer(int):
def __new__(cls, val):
instance = super().__new__(cls, val)
cls._val = val
# Customize your instance here...
return instance
def __add__(self, val):
if isinstance(val, Integer):
return Integer(self._val + val._val)
return Integer(self._val + val)
def __iadd__(self, val):
if isinstance(val, Integer):
return Integer(self._val + val._val)
return Integer(self._val + val)
def __str__(self):
return str(self._val)
def __repr__(self):
return 'Integer(%s)' % self._val
Another modification is always return an Integer instance after math operations as __add__ and __iadd__. Otherwise, the result can be a int and the next time you call a math operation, the standard int methods will be called.
Reference about the __new__ method here.