I have a superclass with the method run()
.
I make a subclass of the superclass that I would like to have its own run()
method. But, I want to keep the functionality of the old run method in a method called oldrun()
on this new object.
How would I go about doing this in Python?
Create a new method with a new name. Copy the code of the old method to it. Delete all the code in the old method and, instead of it, insert a call for the new method. Find all references to the old method and replace them with references to the new one.
The only way to rename a function is to change the code .
method inside the overridden method. Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.
The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. Python super() The super() function allows us to avoid using the base class name explicitly.
You could do it like this:
class Base(object):
def run(self):
print("Base is running")
class Derived(Base):
def run(self):
print("Derived is running")
def oldrun(self):
super().run()
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