Python class that extends int doesn't entirely behave like an int
python
Solution
The secret is all in the `__new__()` method:
>>> class MyInt(int): pass
>>> MyInt.__new__ == int.__new__
True
>>> MyInt.__new__(MyInt, '123456789101234567890')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long
>>> MyInt.__new__(int, '123456789101234567890')
123456789101234567890L
Basically when you instantiate a class the very first thing that happens (before `__init__(self, *args)`) is that `__new__(cls, *args)` is called. It is passed the class object as its first argument. The `__new__` method for `int` (which is inherited by `MyInt`) only performs the conversion to `long` if the class it is passed is `int`. I assume this is to avoid messing up subclasses, since converted `MyInt` to `long` would remove all the special functionality you added.
You should use `long` as your base class if you want integers bigger than `int` can handle.
Problem
I'm seeing some weird behavior when trying to convert a string to a class I wrote that extends `int`. Here's a simple program that demonstrates my problem: ``` class MyInt(int): pass toInt = '123456789123456789123456789' print "\nConverting to int..." print type(int(toInt)) print "\nConverting to MyInt..." print type(MyInt(toInt)) ``` Since `MyInt` is empty, I expected that it would behave exactly like an `int`. Instead, here's the output I got from the program above: ``` Converting to int... <type 'long'> Converting to MyInt... Traceback (most recent call last): File "int.py", line 9, in <module> print type(MyInt(toInt)) OverflowError: long int too large to convert to int ``` The string can't convert to a `MyInt`! What about the way I wrote `MyInt` causes it to behave differently than its base class? In this case, there seems to be some kind of maximum on `MyInt`; are there other properties that get implicitly imposed like this when a built-in class is extended in Python? And, finally, is there a way to change `MyInt` so that it doesn't have this maximum anymore?