Home > OS >  How can I gets inner function value in python?
How can I gets inner function value in python?

Time:05-09

I want to know what is the right syntax to gets the value of the outer_function (like the 1st printing below => the expected result) in python3:

def outer_function():
    def inner_function():
        return u'{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}'
    return inner_function


print(u'{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}')
print(outer_function())

The 1st printing is: {"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}

The 2nd printing is: <function outer_function.<locals>.inner_function at 0x7f1bf20e0dc0>

CodePudding user response:

You should return inner_function() instead of inner_function.

https://www.geeksforgeeks.org/python-invoking-functions-with-and-without-parentheses/

def outer_function():
    def inner_function():
        return u'{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}'
    return inner_function()


print(u'{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}')
print(outer_function())

CodePudding user response:

Currently what returns from the outer_function is the reference to the inner_function. The value you're looking for is the return value of the inner_function, so you need to call it too.

def outer_function():
    def inner_function():
        return '{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}'

    return inner_function


print(outer_function()())

Or:

def outer_function():
    def inner_function():
        return '{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}'

    return inner_function


inner = outer_function()
print(inner)   # same output as you got.
print(inner())

You could also return the return value of the inner_function within the outer_function itself:

def outer_function():
    def inner_function():
        return '{"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}'

    return inner_function()

print(outer_function())
  • Related