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?
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.
This can generally be achieved by two ways. Using Classname: Parent's class methods can be called by using the Parent classname. method inside the overridden method. Using Super(): Python super() function provides us the facility to refer to the parent class explicitly.
Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.
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")
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:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With