how do I properly inherit from a superclass that has a __new__ method?

inheritance, python

Solution

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...

class Parent(object):
    def __new__(cls, value, *args, **kwargs):
        print 'my value is', value
        return object.__new__(cls, *args, **kwargs)

...so children can receive their own:

class Child(Parent):
    def __init__(self, for_parent, my_stuff):
        self.my_stuff = my_stuff

Then, it would work:

>>> c = Child(2, "Child name is Juju")
my value is 2
>>> c.my_stuff
'Child name is Juju'

However, the author of your parent class was not that sensible and gave you this problem:

class Parent(object):
    def __new__(cls, value):
        print 'my value is', value
        return object.__new__(cls)

In this case, just override `__new__` in the child, making it accept optional parameters, and call the parent's `__new__` there:

class Child(Parent):
    def __new__(cls, value, *args, **kwargs):
        return Parent.__new__(cls, value)
    def __init__(self, for_parent, my_stuff):
        self.my_stuff = my_stuff

Problem

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?

Original source

Related problems