6

I have a situation when I need to overwrite parent method but only in one line. My initial code is quite big so I clarify what I mean in an example. I have method from parent:

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

And child:

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

As you can see, two methods are pretty much the same but one line is different. Do I have to write the same code in child method just to print different output or there is dark magic in python how to overwrite only one line?

2 Answers2

9

You can introduce an helper method that you override 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")
Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
4

There isn't a magic way to do so, you have to rewrite the entire method.

Now, of course, there are various workarounds. If you can edit the parent, then you can:

  1. Separate out the part you want to override in the child in a separate method to be re-implemented in the child.
  2. If feasible, pass an argument (or even use a class attribute) to the method to alter the method's behavior.

In your case, method #1 would look like:

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

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

And the child:

class Child(Parent):
    def inner(self):
        print("In the child")
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116