如何从具有__new__方法的超类中正确继承? [英] how do I properly inherit from a superclass that has a __new__ method?
问题描述
假设我们有一个类'Parent',由于某种原因定义了 __ new __
,并且继承了它的类'Child'。
(在我的情况下,我试图继承我无法修改的第三方课程)
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
我的尝试是:
class Child(Parent):
def __init__(self, myArg, argForSuperclass):
Parent.__new__(argForSuperclass)
self.field = myArg
但是
p = Parent("argForSuperclass")
按预期工作
c = Child("myArg", "argForSuperclass")
失败,因为'Child'试图调用 __new __
方法它继承自'Parent'而不是它自己的 __ init __
方法。
fails, because 'Child' tries to call the __new__
method it inherits from 'Parent' instead of its own __init__
method.
为了获得预期的行为,我需要在'Child'中进行哪些更改?
What do I have to change in 'Child' to get the expected behavior?
推荐答案
F首先,完全覆盖 __ new __
并不是最佳做法,以避免这些问题......但我知道,这不是你的错。对于这种情况,覆盖 __ new __
的最佳做法是使其接受可选参数...
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
然后,它会起作用:
>>> 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)
在这种情况下,只需覆盖子项中的 __ new __
,使其接受可选参数,并调用父项的 __ new __
那里:
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
这篇关于如何从具有__new__方法的超类中正确继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!