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.