【问题标题】:Multiple inheritance | Python多重继承 | Python
【发布时间】:2020-12-18 19:42:24
【问题描述】:

为什么在这段代码中没有调用 A:[是因为 mro : left to right then A class should be called?]

class A:
    
     def __init__(self,name):
        print('inside a',name)
        
class B:
    
     def __init__(self,name):
        print('inside b',name)
        
class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

输出:

inside c hello

inside b hello

但是当我这样定义它基本上是一个父类时,它按预期正常工作。[为什么在这里调用一个类]代码:

class D:
    
    def __init__(self,name):
        print('inside d',name)
    
class A(D):
    
     def __init__(self,name):
        print('inside a',name)
        super().__init__(name)
        
class B(D):
    
     def __init__(self,name):
        print('inside b',name)
        super().__init__(name)
        
class C(B,A):
    
    def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

输出:

inside c hello

inside b hello

inside a hello

inside d hello

【问题讨论】:

  • 要让super() 正确使用多重继承,您必须在层次结构中的每个 类中使用它——甚至是基类。

标签: python python-3.x inheritance multiple-inheritance


【解决方案1】:

根据方法解析顺序,成员将在深度优先搜索方法中进行搜索,即在您的第一个示例中:

class A:
    
     def __init__(self,name):
        print('inside a',name)
class B:
    
     def __init__(self,name):
        print('inside b',name)       


class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)
        
c = C('hello')

首先:调用C的构造函数。

第二:因为你有 super().init(name) 在你的类 C ,它会调用它的左父,即 B.

第三:它将尝试向右(C类)但由于您没有在B类中编写super().init(name),因此构造函数A 类的不能被调用,因为它不能从 B 类移动到 Object 类

                            Object
                             /\
                            /  \
                           B    A
                            \  /
                             \/
                             C 

如果你在 B 类中写 super().init(name) ,它会从 Object 类迭代到对象的右边,即 A 类

例如:

class A:
    
     def __init__(self,name):
        print('inside a',name)
        
class B:

     def __init__(self,name):
        print('inside b',name)
        super().__init__(name)

        
class C(B,A):
    
     def __init__(self,name):
        print('inside c',name)
        super().__init__(name)

        
c = C('hello')

更多信息请访问:https://www.geeksforgeeks.org/method-resolution-order-in-python-inheritance/

【讨论】:

猜你喜欢
  • 2021-08-05
  • 1970-01-01
  • 2021-05-16
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2012-08-08
  • 2021-05-08
相关资源
最近更新 更多