Let's say we have the following classes:
class Base(object):
def load(self):
# do logic A
# do logic B
class Child(Base):
def load(self):
# do logic C
I know decorators can be used to extend function behavior in Python but I don't know how I can apply it in my case.
When Child's
load()
is called, how can I get the following code executions in this order?:
logic A
logic C
logic B
What I don't want to do
class Base(object)
def logicA()
pass
def logicB()
pass
def load()
pass
class Child(Base):
def load(self):
super.logicA()
# do logic C
super.logicB()
I just want to code up logic C, without having to explicitly call logic A and B
In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism.
extend() is Python's built-in function. It iterates over the specified iterable and appends its elements to the end of the current list. The list. extend() method is equivalent to list[len(list):] = iterable (appends the elements of the iterable after the list's last element).
The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another.
When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
You mean something like this:
class Base(object):
def load(self):
print('do logic A')
print('do logic B')
class Child(Base):
def load(self):
super().load()
print('do logic C')
c = Child()
c.load()
This will print:
do logic A
do logic B
do logic C
The only other way I can think of is this one:
class Base(object):
def load(self):
print('do logic A')
self.new_logic() # call new logic from child class, if exist.
print('do logic B')
def new_logic(self):
# overwrite this one in child class
pass
class Child(Base):
def new_logic(self):
print('do logic C')
c = Child()
c.load()
This prints:
do logic A
do logic C
do logic B
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