1

我有以下实现多重继承的代码。我希望调用super(base2,self).__init__()打印--> "Printing from base2".但是程序什么也没打印;它也不会引发错误。

class base1:
    def __init__(self):
        print("printing from base1")
    
    def method(self,val):
        print("From method of base1", val)

class base2:
    def __init__(self):
        print("printing from base2")
    
    def method(self,val):
        print("From method of base2", val)
        
class child(base1, base2):
    def __init__(self):
        super(base2,self).__init__()  #is not working as expected
        
        
x = child() 
4

1 回答 1

2

The call to super expects the child class as its first param, not the base class. You should be doing

super(child, self).__init__()

However, since python 3.0, you can simply do

super().__init__()

But how does this play into multiple inheritence? Well that's extremely well explained in this answer

Basically, in your case, changing super to the appropriate call will yield the base1 class' __init__ call. According to the MRO (method resolution order).

What if you wanted to invoke the __init__ of base2? Well you're looking into directly calling base2.__init__() in that case, or simply changing the order of inheritance.

class child(base2, base1):
    def __init__(self):
        super().__init__()

Now this will print the base2 class' __init__ method

于 2020-06-27T08:01:49.760 回答