在 python 中部分覆盖 parent 方法

overwrite parent method partially in python

我有一种情况需要覆盖 parent 方法,但只能覆盖一行。我的初始代码非常大,所以我在示例中阐明了我的意思。 我有来自 parent:

的方法
class parent():
    def method(self):
        bla
        bla
        print("Parent method is working")
        bla
        bla

和child:

class child(parent):
    def method(self):
        bla
        bla
        print("Child method working")
        bla
        bla

如您所见,两种方法几乎相同,但一行不同。我是否必须在 child 方法中编写相同的代码来打印不同的输出,或者 python 中有黑魔法如何只覆盖一行?

没有什么神奇的方法可以做到这一点,您必须重写整个方法。

当然,现在有各种解决方法。如果您可以编辑 parent,那么您可以:

  1. 在 child 中用单独的方法将要覆盖的部分分离为 child 中的 re-implemented。
  2. 如果可行,将参数(或什至使用 class 属性)传递给方法以改变方法的行为。

在您的情况下,方法 #1 如下所示:

class Parent(object):
     def method(self):
         print("Before!")
         self.inner()
         print("After!")

     def inner(self):
         print "In the parent"

和child:

class Child(Parent):
    def inner(self):
        print("In the child")

您可以引入一个您在子项中重写的辅助方法。

class parent(object):
  def method(self):
    blah
    self.helper()
    blah
  def helper(self):
    print("parent running")

class child(parent):
  def helper(self):
    print("child running")