在多重继承中没用的超级? [英] useless super in multiple inheritance?

查看:79
本文介绍了在多重继承中没用的超级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多重继承中super()是如何工作的? 例如,这里我有两个 init ,我想通过super()发送args:

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)

但有错误:

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

但是此代码有效:

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

super()可以在多个继承中工作吗?

so super() dosent work in multiple inheritance??

推荐答案

super在多重继承中工作正常;实际上,这正是它的目的.但是由于某种原因,您使用不同的参数两次调用它.那不是它的工作原理.

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.

调用一次.这将按方法解析顺序调用下一个方法.然后,该方法的责任调用super,以调用下一个方法.

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.

请阅读Raymond Hettinger的经典文章超级被认为超级

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

这篇关于在多重继承中没用的超级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆