Extending Legacy Function Behavior in Python

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 that decorators can be used to extend the behavior of functions 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

 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 encode logic C without having to explicitly call logic A and B

+6
source share
1 answer

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 way I can think of is this:

 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() 

Fingerprints:

 do logic A do logic C do logic B 
+3
source

Source: https://habr.com/ru/post/983244/


All Articles