useless super in multiple inheritance? [duplicate]

本秂侑毒 提交于 2020-01-22 03:26:27

问题


in multiple inheritance how super() works? for example here I have Two init and I want to send args by super():

class LivingThings(object):
    def __init__(self, age ,name):
        self.name=name
        self.age=age

    def Print(self):
        print('age: ', self.age)
        print('name: ', self.name)

class Shape(object):
    def __init__(self, shape):
        self.shape=shape
    def Print(self):
        print(self.shape)

class Dog(LivingThings, Shape):
    def __init__(self, breed, age , name, shape):
        self.breed=breed
        super().__init__(age , name)
        super().__init__(shape)


    def Print(self):
        LivingThings.Print(self)
        Shape.Print(self)
        print('breed', self.breed)

but error :

super().__init__(shape)
TypeError: __init__() missing 1 required positional argument: 'name'

but this code works :

class Dog(LivingThings, Shape):
    def __init__(self, breed, age , name, shape):
        self.breed=breed
        Shape.__init__(self, shape)
        LivingThings.__init__(self,age ,name)

so super() dosent work in multiple inheritance??


回答1:


super works fine in multiple inheritance; that is in fact precisely what it is for. But for some reason you are calling it twice, with different arguments; that is not how it works.

Call it once. That calls the next method in the method resolution order. It is then that method's responibility to call super, to call the next method.

Please read Raymond Hettinger's classic article Super considered super.



来源:https://stackoverflow.com/questions/32805738/useless-super-in-multiple-inheritance

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