多重继承如何与super()和不同的__init __()参数一起使用?

发布于 2021-01-29 15:08:19

我只是在研究一些更高级的python主题(至少对我来说是高级的)。我现在正在阅读有关多重继承以及如何使用super()的信息。我或多或少了解超级函数的使用方式,但是
(1)像这样做是 怎么回事?:

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

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

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

关于super(),关于Python Warts的Andrew
Kuchlings论文
说:

当Derived类继承自多个基类并且其中一些或全部具有 init 方法时,super()的用法也将是正确的

因此,我将上面的示例重写如下:

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

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

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

但是,这只会运行它可以找到的第一个 initFirst(2)可以super()用来同时运行fromFirst和的init
Second,如果可以,如何运行?
运行super(Third, self).__init__(self)两次只会先运行。 初始化
()两次。

再增加一些混乱。如果继承的类的 init ()函数采用不同的参数怎么办。例如,如果我有这样的事情怎么办:

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

class Second(object):
    def __init__(self, y, z):
        print "second"

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

(3)如何使用super()为不同的继承类init函数提供相关的参数?

欢迎所有提示!

ps。由于我有几个问题,因此我将它们加粗并编号。

关注者
0
被浏览
97
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    对于问题2,您需要在每个类中调用super:

    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"
    

    对于问题3,这无法完成,您的方法需要具有相同的签名。但是您可以忽略父句中的某些参数或使用关键字参数。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看