简体   繁体   中英

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. Since F2() is recursive, I have to store variables outside.

In C I would separate both or pass pointers, in Java I would create objects. But is there anyway in Python that allows me to do this quickly without much changes? I don't want to use global variables, myvar needs to be kept within the context of F1()

Thank you.

You can use nonlocal variables:

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. myArrayVar is just a closure variable, since you don't rebind the name it needs no special treatment.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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