Search code examples
pythonfunctioninheritanceoverridingdecorator

Extending the behavior of an inherited function in Python


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


Solution

  • 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