How does multiple inheritance work with the super() and different __init__() arguments?

时间秒杀一切 提交于 2019-11-29 21:31:27

For question 2, you need to call super in each class:

class First(object):
    def __init__(self):
        super(First, self).__init__()
        print "first"

class Second(object):
    def __init__(self):
        super(Second, self).__init__()
        print "second"

class Third(First, Second):
    def __init__(self):
        super(Third, self).__init__()
        print "that's it"

For question 3, that can't be done, your method needs to have the same signature. But you could just ignore some parameters in the parent clases or use keywords arguments.

Vb407

1) There is nothing wrong in doing like what u have done in 1, if u want to use the attributes from base class then u have to call the base class init() or even if u r using methods from base class that uses the attributes of its own class then u have to call baseclass init()

2) You cant use super to run both the init's from First and Second because python uses MRO (Method resolution order)

see the following code this is diamond hierarchy

class A(object): 
    def __init__(self):
        self.a = 'a'
        print self.a

class B(A):
    def __init__(self):
        self.b = 'b'
        print self.b

class C(A):
    def __init__(self):
        self.c = 'c'
        print self.c

class D(B,C):
    def __init__(self):
        self.d = 'd'
        print self.d
        super(D, self).__init__()

d = D()
print D.mro()

It prints:

d
b
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>]

MRO of python would be D,B,C,A

if B does't have init method it goes for C.

3) You can't do it all methods need to have same signature.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!