简体   繁体   English

Python 如何使用(function F1 内部的变量) function 内部(F2 在 F1 内部)

[英]Python how to use (variables inside function F1) inside function (F2 which is inside F1)

def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        global myvar, myArrayVar # this will be changed by F2()
        myvar = 2
        myArrayVar.append(myVar)
        print(myvar)
    F2()

F1()

So I have a function inside a function.所以我在 function 中有一个 function。 Since F2() is recursive, I have to store variables outside.由于 F2() 是递归的,我必须将变量存储在外部。

In C I would separate both or pass pointers, in Java I would create objects.在 C 中,我将两者分开或传递指针,在 Java 中,我将创建对象。 But is there anyway in Python that allows me to do this quickly without much changes?但无论如何,在 Python 中是否有允许我快速完成此操作而无需太多更改? I don't want to use global variables, myvar needs to be kept within the context of F1()我不想使用全局变量, myvar需要保存在F1()的上下文中

Thank you.谢谢你。

You can use nonlocal variables:您可以使用nonlocal变量:

def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        nonlocal myvar, myArrayVar  # this will be changed by F2()
        myvar = 2
        myArrayVar.append(myvar)

    F2()
    print(myvar)
    print(myArrayVar)

F1()
2
[2]

Actually only myvar needs to be declared a nonlocal variable here.实际上这里只需myvar声明为非 局部变量。 myArrayVar is just a closure variable, since you don't rebind the name it needs no special treatment. myArrayVar只是一个闭包变量,因为您不重新绑定它不需要特殊处理的名称。

def F1():
    myvar = 1
    myArrayVar = []

    def F2():
        nonlocal myvar  # allows changes to myvar to be seen by the outer scope
        myvar = 2
        myArrayVar.append(myvar)
        print(myvar)
    F2()

F1()

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

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