繁体   English   中英

如何在 python 中获取内部 function 值?

[英]How can I gets inner function value in python?

我想知道在 python3 中获取outer_function值的正确语法是什么(如下面的第一次打印 =>预期结果):

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())

第一次打印是: {"f1":["x1", "y1", "z1"], "f2":["x2", "y2", "y3"]}

第二次打印是: <function outer_function.<locals>.inner_function at 0x7f1bf20e0dc0>

您应该返回 inner_function() 而不是 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())

目前从outer_function inner_function引用。 您要查找的值是inner_function的返回值,因此您也需要调用它。

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

    return inner_function


print(outer_function()())

或者:

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())

您还可以在outer_function本身中返回inner_function的返回值:

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

    return inner_function()

print(outer_function())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM