简体   繁体   中英

How to make variable accessible inside another function

Consider this example:

def func1():
    val = 1
    res = [1]
    def fun2():
        print(res)
        print(val)
        val = 2 
    fun2()
    print(val)

func1()

It raises the following exception:

UnboundLocalError: local variable 'val' referenced before assignment

List res can be accessed by fun2 , but val cannot. I know list is mutable and int is not, but is there a way to make val accessible by fun2 as well? In a class, I could easily achieve that with self.val , but is there a way to do it inside a function?

Use the nonlocal statement to make a variable defined in an enclosing function accesible inside the inner function, like so:

def func1():
    val = 1
    res = [1]
    def fun2():
        nonlocal val
        print(res)
        print(val)
        val = 2 
    fun2()
    print(val)

func1()

See also: earlier SO question .

You can do it in the following way:

def func1():
    val = 1
    res = [1]
    def fun2(val=val, res=res):
        print(res)
        print(val)
        val = 2 
        return val
    val = fun2()
    print(val)

Output is then

>>> func1()
[1]
1
2

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