假设我们有一个类 'Parent' ,由于某种原因定义了 __new__
和一个继承自它的类 'Child'。
(在我的例子中,我试图从我无法修改的第 3 方类继承)
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”试图调用它从“Parent”继承的 __new__
方法而不是它自己的 __init__
方法。
我必须在“Child”中更改什么才能获得预期的行为?
最佳答案
首先,为避免这些问题而完全覆盖 __new__
不被认为是最佳实践......但这不是你的错,我知道。对于这种情况,覆盖 __new__
的最佳做法是让它接受可选参数...
class Parent(object):
def __new__(cls, value, *args, **kwargs):
print 'my value is', value
return object.__new__(cls, *args, **kwargs)
...所以 children 可以收到他们自己的:
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'
但是,你的父类的作者不太懂事,给你出了这个问题:
class Parent(object):
def __new__(cls, value):
print 'my value is', value
return object.__new__(cls)
在这种情况下,只需覆盖子项中的 __new__
,使其接受可选参数,并在那里调用父项的 __new__
:
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
关于python - 我如何正确地继承具有 __new__ 方法的父类(super class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10788976/