Why can't *args be passed to super().__init__() from class that overrides int?

Viewed 203
class MyInt(int):
   def __new__(cls, *args, **kwargs):
       print(repr(args), repr(kwargs))
       return super(MyInt, cls).__new__(cls, *args, **kwargs)
   def __init__(self, *args, **kwargs):
       print(repr(args), repr(kwargs))
       return super(MyInt, self).__init__(*args, **kwargs)

MyInt(1)

This code outputs:

(1,) {}
(1,) {}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-a45744cab1af> in <module>()
----> 1 MyInt(1)

<ipython-input-3-a38fc9aae2fe> in __init__(self, *args, **kwargs)
      5     def __init__(self, *args, **kwargs):
      6         print(repr(args), repr(kwargs))
----> 7         return super(MyInt, self).__init__(*args, **kwargs)
      8 

TypeError: object.__init__() takes no parameters

It seems the base __init__() is expecting for args, because I can print them. So why can't I just pass them forward to the method of base class? (Btw, this worked fine in python 2.7)

1 Answers

As int object is immutable, you can't use the __init__ method. As it's explained in this documentation, you only have to use __new__.

Here it prioritises the __init__ method when you create a new MyInt, and this is why you get the error. So just take off the __init__ method and keep the __new__ one.

Hope I got useful.

Related