【问题标题】:How can I override two methods that call each other, while using super() to access base class methods? [duplicate]如何在使用 super() 访问基类方法时覆盖两个相互调用的方法? [复制]
【发布时间】:2018-05-02 15:34:52
【问题描述】:

我有两个 Python3 类:

class A:
    def f1(self):
        self.f2()

    def f2(self):
        pass

class B(A):
    def f1(self):
        super().f1()

    def f2(self):
        pass

我希望 super().f1() 调用在内部也调用 A 的 f2()。然而,它最终调用了 B 的 f2()。我该如何更改?

【问题讨论】:

    标签: python oop inheritance overloading super


    【解决方案1】:

    当前行为是继承机制的预期行为。但是你可以手动选择在A类中调用哪个方法:

    class A:
        def f1(self):
            A.f2(self)
    
        def f2(self):
            pass
    

    【讨论】:

      【解决方案2】:

      我认为最简单的方法是在 A 中创建一个“隐藏”方法(按照惯例,these are prefixed with _:

      class A:
          def f1(self):
              self._f2()
      
          def f2(self):
              print("A's f2")
              self._f2()
      
          def _f2(self):
              print("A's _f2")
      
      
      class B(A):
          def f1(self):
              super().f1()
      
          def f2(self):
              print("B's f2")
              pass
      
      
      b = B()
      
      b.f1()  # prints: A's _f2
      

      这样做的好处是,如果出于某种原因需要,您仍然可以覆盖 B 中的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-09
        • 2012-05-01
        • 1970-01-01
        • 2016-05-20
        • 1970-01-01
        • 1970-01-01
        • 2022-11-25
        • 2013-03-03
        相关资源
        最近更新 更多