Home > Enterprise >  Python: Calling Inner Function Within Outer Function Within a Class
Python: Calling Inner Function Within Outer Function Within a Class

Time:04-07

I have a class object with a method function. Inside this method function "animal", I have an inner function that I want to call. But it appears that my inner function isn't being called because the correct result should return "hit here" instead of "sample text".

Here is my class code:

class PandaClass(object):
    def __init__(self, max_figure):
        self.tree = {}
        self.max_figure = max_figure
        
    def animal(self, list_sample, figure):
        
        def inner_function():
            if len(list_sample) == 0:
                return "hit here"
        inner_function()
        
        return "sample text" 

I instantiate the class and call the animal function with code below:

panda = PandaClass(max_figure=7)
panda.animal(list_sample=[], figure=0)

I want the code to return "hit here" which would mean the inner function got run but instead I got "sample text". Please let me know how I can correct this.

CodePudding user response:

return always gives its result to the code that called it. In this case, the outer function called the inner function, so the inner function is returning it's value to the outer function.

If you want the outer function to return the result that the inner function returns, you need to do something like this:

    def animal(self, list_sample, figure):
        
        def inner_function():
            if len(list_sample) == 0:
                return "hit here"
        inner_func_result = inner_function()
        
        
        if inner_func_result:
            return inner_func_result
        else:
            return "sample text" 
  • Related