0

Let's say I have a class that inherits from int.

class Test(int):
    def __init__(self, val: int, extra: str) -> None:
        print("reached")
        self.val = val
        int.__init__(self, val)

def main():
    myTest = Test(3, "hi")
    print(myTest.val)

if __name__ == "__main__":
    main()

Now, I would expect that my code would output "reached" because I'm calling the constructor for Test. However, I get the following error:

Traceback (most recent call last):
  File "C:/.../Test.py", line 46, in <module>
    myTest = Test(3, "hi")
TypeError: 'str' object cannot be interpreted as an integer

and "reached" never outputs! As far as I know, my code should call the __init__ function I have defined before it calls int's constructor, but obviously that's not happening.

It looks more like the code is calling the superclass constructor before it calls mine, which I find quite strange. Is this indeed what is happening?

What is the best way for me to add additional parameters to the __init__(...) declaration without getting these sorts of errors?

Before you mark this as a duplicate, I am familiar with similar questions, but none of them address why this is happening. Also, a lot of them use multiple inheritance. I'm trying to figure out why, when using single inheritance of a primitive type, the code appears to call the parent's constructor instead of the one that should override it.

JustDucky
  • 132
  • 1
  • 10
  • 1
    what exactly are you trying to do here? this line `int.__init__(self, val)` doesn't make much sense – gold_cy Apr 24 '20 at 21:37
  • Does this answer your question? [Subclassing int in Python](https://stackoverflow.com/questions/3238350/subclassing-int-in-python) – r.ook Apr 24 '20 at 21:40
  • The int.__init__(self, val) code is not executed. You're right, it doesn't make much sense, but the problem is that it is never reached. – JustDucky Apr 24 '20 at 22:54
  • The question you linked looks like it deals with a similar issue as my code, but it doesn't answer the big question here: why isn't the constructor I wrote called before int's constructor? – JustDucky Apr 24 '20 at 22:59

0 Answers0