【问题标题】:How to call a method from base class a few levels up in the inheritance chain?如何从继承链中的几个级别调用基类中的方法?
【发布时间】:2017-08-20 21:16:54
【问题描述】:

假设我们有以下继承链:

class Base:
    def method(self):
        # …

class Derived1(Base):
    def method(self):
        # …

class Derived2(Derived1):
    pass

class Derived3(Derived2):
    def method(self):
        # …

问题:我想以某种方式在Derived3 中定义method,以便它从Base 调用自身。

通常我只会写:

class Derived3(Derived2):
    super().method()

但这会从Derived1 调用method,这正是我想要避免的。我想从Base 打电话给method

【问题讨论】:

    标签: python python-3.x inheritance base-class


    【解决方案1】:

    最简单的方法是直接调用Base方法,显式传递self

    Base.method(self)
    

    如果目标是跳到“MRO 中某个已知的坏超类之后的任何内容”,您可以使用带有显式参数的 super,就好像它是从“坏超类”调用的一样,所以它移动到“无论接下来发生什么”:

    class Derived3(Derived2):
        def method(self):
            # Call method from next class after Derived1 in MRO, which happens to be Base
            # Using super means the method is bound, so self passed implicitly to method
            super(Derived1, self).method()
    

    【讨论】:

      【解决方案2】:

      您可以显式调用超类的成员,只需将self 作为第一个参数传递:

      Base.method(self)
      

      完整示例:

      class Derived3(Derived2):
          def method(self):
              Base.method(self)
      

      这将在self指定的实例上执行Base.method,在访问through an instance时自动传递给Derived3.method

      【讨论】:

        猜你喜欢
        • 2015-07-15
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多