Extending the behavior of an inherited function in Python

10,172

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
Share:
10,172
lambda
Author by

lambda

Currently working on scientific applications.

Updated on June 03, 2022

Comments

  • lambda
    lambda almost 2 years

    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

    • thefourtheye
      thefourtheye about 9 years
      Split logic A and B in to two different functions?
  • lambda
    lambda about 9 years
    Close, but I am aiming for logic C to be called before B
  • lambda
    lambda about 9 years
    But the thing is, I don't want to explicitly be calling logic A or B...logic C is basically just an extension of the Base load()
  • Paul Rooney
    Paul Rooney about 9 years
    @Unit978 You are saying you want the child function to execute in the middle of the base classes function ?
  • Paul Rooney
    Paul Rooney about 9 years
    Maybe pass a function to perform logic C to the base class function and call it in between logic A and Logic B?
  • lambda
    lambda about 9 years
    The thing is, I don't want to explicitly call anything from the Base class.
  • Marcin
    Marcin about 9 years
    @Unit978 I amended the answer with other possibility.