Let’s assume we have a class ‘Parent’ , that for some reason has __new__ defined and a class ‘Child’ that inherits from it.
(In my case I’m trying to inherit from a 3rd party class that I cannot modify)
class Parent:
def __new__(cls, arg):
# ... something important is done here with arg
My attempt was:
class Child(Parent):
def __init__(self, myArg, argForSuperclass):
Parent.__new__(argForSuperclass)
self.field = myArg
But while
p = Parent("argForSuperclass")
works as expected
c = Child("myArg", "argForSuperclass")
fails, because ‘Child’ tries to call the __new__ method it inherits from ‘Parent’ instead of its own __init__ method.
What do I have to change in ‘Child’ to get the expected behavior?
Firstly, it is not considered best practice to override
__new__exactly to avoid these problems… But it is not your fault, I know. For such cases, the best practice on overriding__new__is to make it accept optional parameters……so children can receive their own:
Then, it would work:
However, the author of your parent class was not that sensible and gave you this problem:
In this case, just override
__new__in the child, making it accept optional parameters, and call the parent’s__new__there: