Python 多继承,__init__

标签 python oop inheritance init super

关于多父继承,当我调用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/

相关文章:

Python HTTP SSL 服务器接受连接速度慢

java - 将 Python POST 请求转换为 Android

python - 如何根据已知直线分割OpenCV轮廓?

python - 在 python 中处理坐标的最合适的变量类型

php - 你能在一节课中扩展两个类吗?

c# - C#创建一个对象时,会在内存中创建一个类中的多少个方法?

c++ - 通过继承的类模板 SFINAE

c++ - 函数模板特化失败

javascript - 如何在 Javascript 中测试多重继承

java - java中if循环内的返回类型