有没有办法在Python中使用内部函数体中的外部函数变量?

时间:2018-05-23 10:47:23

标签: python ironpython

我尝试构建的代码模式是:

def OuterFunction():
    theVariable = 0

    def InnerFunction():
        # use theVariable from OuterFunction somehow

    # the solution is not to use InnerFunction(theVariable) due to the reasons given in the text
    InnerFunction()

我希望有一些关键字(如全局)或告诉解释器使用外部方法范围内的变量的方法。

为什么我需要这样: 我们之前运行的Python脚本现在必须成为模块(方法集合)。

以前不存在OuterFunction,而InnerFunction只是大量具有已有逻辑的非常复杂的方法的一个例子。

theVariable只是在InnerFunction所代表的所有方法中脚本中使用的多个全局变量的一个示例。

我不想更改所有方法的签名,顺便说一下,嵌套。

编辑:

以下是在每个解释器中崩溃的代码,在分配之前引用“局部变量'theVariable'错误(因此我不能仅引用变量):

def OuterFunction():

    theVariable = 5

    def InnerFunction():
        theVariable = theVariable + 1
        print(theVariable)

    InnerFunction()

OuterFunction()

EDIT2:

似乎试图更改变量会导致异常,这会给出错误的描述。 如果将InnerFunction()更改为仅包含print(theVariable)语句,则它可以工作。

3 个答案:

答案 0 :(得分:2)

如果你不想将它的值作为参数传递,你可以简单地引用嵌套的InnerFunction中的'theVariable':

def OuterFunction():
    # Declare the variable
    theVariable = 42

    def InnerFunction():
        # Just reference the 'theVariable', using it, manipulating it, etc...
        print(theVariable)

    # Call the InnerFunction inside the OuterFunction
    InnerFunction()

# Call the OuterFunction on Main
OuterFunction()

# It will print '42' as result

答案 1 :(得分:1)

您可以直接引用变量,如下所示;

def outer():
    x = 1
    def inner():
        print(x + 2)
    inner()
outer()

打印:3

答案 2 :(得分:0)

这对你没关系:

def OuterFunction():
    theVariable = 0
    def InnerFunction(value):
        return value + 1
    theVariable = InnerFunction(theVariable)
    return theVariable

通过这种方式,您不必弄乱范围,而且您的功能