【问题标题】:Python Multiple Inheritance ExamplePython 多重继承示例
【发布时间】:2015-12-13 11:58:00
【问题描述】:

我有这种情况

class A(object):

    def __init__(self):
        self.x = 0
        self.y = 0

class B(A):
    def __init__(self):
        super(B, self).__init__()

    def method(self):
        self.x += 1

class C(A):

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

    def method(self):
        self.y += 1

class D(B, C):

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

    def method(self):
        print self.x
        print self.y

我希望 D 为 x 和 y 都打印 1,但它正在打印 0。
我不完全理解多重继承/超级/等...虽然我一直在尝试阅读文档,但对示例的解释对我很有帮助。

谢谢!

【问题讨论】:

    标签: python class python-2.7 multiple-inheritance super


    【解决方案1】:

    如果您在示例中重写了类似method 的方法,但仍想获得基类的行为以及您自己的行为,则需要使用super 来调用您正在使用的方法的版本覆盖。

    class A(object):
        def __init__(self):
            self.x = 0
            self.y = 0
    
        def method(self):  # we need a verion of method() to end the super() calls at
            pass
    
    class B(A):
        def method(self):
            super(B, self).method() # call overridden version of method()
            self.x += 1
    
    class C(A):
        def method(self):
            super(C, self).method() # here too
            self.y += 1
    
    class D(B, C):
        def method(self):
            super(D, self).method() # and here
            print self.x
            print self.y
    

    我已经删除了您子类中不必要的 __init__ 方法。除非您更改其行为,否则无需重写方法,并且后来的 __init__ 方法除了调用它们的前任之外没有做任何事情。

    【讨论】:

      【解决方案2】:

      当你创建一个 D 对象时,它永远不会调用名为“方法”的方法。 它只会调用父级的 'init' 方法。所以 x 或 y 不会改变。

      【讨论】:

        【解决方案3】:

        你也可以在你的 D 子类中调用继承类的方法 D类(B,C):

        def __init__(self):
            B.__init__(self)
            C.__init__(self)
        
        def method(self):
            B.method(self)
            C.method(self)
            print(self.x)
            print(self.y)
        

        【讨论】:

          猜你喜欢
          • 2020-07-04
          • 2017-08-21
          • 1970-01-01
          • 2020-12-18
          • 2021-08-05
          • 1970-01-01
          • 2021-05-16
          • 2015-05-02
          • 1970-01-01
          相关资源
          最近更新 更多