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

后端 未结 3 684
我寻月下人不归
我寻月下人不归 2021-01-11 17:55

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 inh

3条回答
  •  执笔经年
    2021-01-11 18:59

    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
    

提交回复
热议问题