0

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.

3
  • 1
    You return the string from your inner function but do nothing with this result Commented Apr 6, 2022 at 1:57
  • I don't quite understand; can you give me an example of how I would do something with the result? Commented Apr 6, 2022 at 1:58
  • 1
    Return the result of inner_function() if it is not None? A one-liner would look like this return inner_function() or "sample text" or you could save the result and have an if/else Commented Apr 6, 2022 at 2:00

1 Answer 1

1

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" 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.