gpt4 book ai didi

Python 多继承,__init__

转载 作者:IT老高 更新时间:2023-10-28 22:15:16 32 4
gpt4 key购买 nike

关于多父继承,当我调用super.__init__时,为什么没有调用parent2的__init__函数?谢谢。

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

最佳答案

如果你想在child中使用super来调用parent.__init__parent2._init__,那么两个父 __init__ 也必须调用 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 super method and calling alternatives"有关使用 super 引起的对 __init__ 的调用顺序的更多详细信息。


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?”。如果 parentparent2 直接继承自 object,那么super(parent2,self).__init__(x,y) 会调用 object.__init__(x,y)。这会引发 TypeError 因为 object.__init__() 没有参数。

要解决此问题,您可以创建一个类 Base,该类接受 __init__ 的参数但不将它们传递给 object.__init__ .使用从 Base 继承的 parentparent2,您可以避免 TypeError

关于Python 多继承,__init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8688114/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com