多重继承:派生类仅从一个基类获取属性? [英] Multiple inheritance: The derived class gets attributes from one base class only?

查看:120
本文介绍了多重继承:派生类仅从一个基类获取属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图学习Python中的多重继承的概念.考虑从两个类Base1Base2派生的类Derv. Derv仅继承第一个基类的成员:

I was trying to learn the concepts of multiple-inheritance in Python. Consider a class Derv derived from two classes, Base1 and Base2. Derv inherits members from the first base class only:

class Base1:
    def __init__(self):
        self.x=10

class Base2:
    def __init__(self):
        self.y=10

class Derv (Base1, Base2):
    pass

d = Derv()
print (d.__dict__)

结果为{ 'x' : 10 },颠倒继承顺序仅给出{ 'y' : 10 }.

The result is { 'x' : 10 } and reversing the order of inheritance gives only { 'y' : 10 }.

派生类是否应该继承两个基类的属性?

Shouldn't the derived class inherit attributes from both the base classes?

推荐答案

我不完全理解为什么会这样,但是我可以告诉您如何解决它:

I don't fully understand why it's like this, but I can tell you how to fix it:

由于某种原因,Python仅调用其父级之一的__init__方法.但是,这可以解决您的问题:

For some reason, Python only calls the __init__ method of one of it's parents. However, this fixes your problem:

class Base1:
     def __init__(self):
         super().__init__()
         print('b1')
         self.x=10

 class Base2:
     def __init__(self):
         super().__init__() # This line isn't needed. Still not sure why
         print('b2')
         self.y=10

 class Derv (Base1, Base2):

     def __init__(self):
         super().__init__()

 d = Derv()
 print (d.__dict__)


'b2'
'b1'
{'y': 10, 'x': 10}


更新,添加打印语句实际上可以说明情况.例如


Update, adding print statements actually sheds some light on the situation. For example,

class Base1:
     def __init__(self):
         print('Before Base1 call to super()')
         super().__init__()
         print('b1')
         self.x=10

 class Base2:
     def __init__(self):
         print('Before Base2 call to super()')
         super().__init__() # No remaining super classes to call
         print('b2')
         self.y=10

 class Derv (Base1, Base2):

     def __init__(self):
         super().__init__()

 d = Derv()
 print (d.__dict__)

'Before Base1 call to super()' # Just before the call to super
'Before Base2 call to super()' # Just before call to super (but there are no more super classes)
'b2' # Calls the remaining super's __init__
'b1' # Finishes Base1 __init__
{'y': 10, 'x': 10}

这篇关于多重继承:派生类仅从一个基类获取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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