Python多继承,__ init__ [英] Python multi-inheritance, __init__
问题描述
关于多父继承,当我调用 super
。 __ init __
时,为什么不将parent2的 __ init __
函数被调用?谢谢。
Regarding multiple parent inheritance, when I call the super
.__init__
, why doesn't parent2's __init__
function get called? Thanks.
class parent(object):
var1=1
var2=2
def __init__(self,x=1,y=2):
self.var1=x
self.var2=y
class parent2(object):
var4=11
var5=12
def __init__(self,x=3,y=4):
self.var4=x
self.var5=y
def parprint(self):
print self.var4
print self.var5
class child(parent, parent2):
var3=5
def __init__(self,x,y):
super(child, self).__init__(x,y)
childobject = child(9,10)
print childobject.var1
print childobject.var2
print childobject.var3
childobject.parprint()
输出
9
10
5
11
12
推荐答案
如果你想使用 super
在 child
中调用 parent .__ init __
和 parent2._ini t __
,那么父 __ init __
s也必须调用 super
:
If you want to use super
in child
to call parent.__init__
and parent2._init__
, then both parent __init__
s must also call super
:
class parent(Base):
def __init__(self,x=1,y=2):
super(parent,self).__init__(x,y)
class parent2(Base):
def __init__(self,x=3,y=4):
super(parent2,self).__init__(x,y)
参见Python超级方法和调用替代方法,了解有关使用<$ c导致的 __ init __
调用顺序的更多详细信息$ c> super 。
See "Python super method and calling alternatives" for more details on the sequence of calls to __init__
caused by using super
.
class Base(object):
def __init__(self,*args):
pass
class parent(Base):
var1=1
var2=2
def __init__(self,x=1,y=2):
super(parent,self).__init__(x,y)
self.var1=x
self.var2=y
class parent2(Base):
var4=11
var5=12
def __init__(self,x=3,y=4):
super(parent2,self).__init__(x,y)
self.var4=x
self.var5=y
def parprint(self):
print self.var4
print self.var5
class child(parent, parent2):
var3=5
def __init__(self,x,y):
super(child, self).__init__(x,y)
childobject = child(9,10)
print childobject.var1
print childobject.var2
print childobject.var3
childobject.parprint()
您可能想知道,为什么要使用 Base
?。如果 parent
和 parent2
直接从对象
继承,那么
super(parent2,self).__ init __(x,y)
将调用 object .__ init __(x,y)
。因为 object .__ init __()
没有参数,所以引发 TypeError
。
You might be wondering, "Why use Base
?". If parent
and parent2
had inherited directly from object
, then
super(parent2,self).__init__(x,y)
would call object.__init__(x,y)
. That raises a TypeError
since object.__init__()
takes no parameters.
要解决此问题,您可以创建一个类 Base
,它接受 __ init __
的参数但不将它们传递给 object .__ init __
。使用 parent
和 parent2
继承自 Base
,您可以避免 TypeError
。
To workaround this issue, you can make a class Base
which accepts arguments to __init__
but does not pass them on to object.__init__
. With parent
and parent2
inheriting from Base
, you avoid the TypeError
.
这篇关于Python多继承,__ init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!