You can subclass int
, but because it is immutable you need to provide a .__new__() constructor hook:
class MyInt(int):
def __new__(cls, value):
new_myint = super(MyInt, cls).__new__(cls, value)
return new_myint
You do need to call the base __new__
constructor to get your subclass properly created.
In Python 3, you can omit the arguments to super()
altogether:
class MyInt(int):
def __new__(cls, value):
new_myint = super().__new__(cls, value)
return new_myint
Of course, this assumes you wanted to manipulate value
before passing in to super().__new__()
or manipulate new_myint
some more before returning; otherwise you may as well remove the whole __new__
method and just implement this as class MyInt(int): pass
.