我相信我知道这个问题的答案,但想仔细检查一下,因为我发现这有点令人困惑。
def outerFunc():
mySet = set()
a = 0
def innerFunc():
mySet.add(1)
mySet.add(2)
a = 7
innerFunc()
print(mySet) # {1, 2}
print(a) # 0
这里,如果我想改变a
的值,我需要使用nonlocal
。集合发生变化的事实只是因为集合是通过引用传递的?那么,在内部函数中,我们可以访问外部函数变量的值,但不能修改它们,除非它们是引用?
最佳答案
可以查看python document
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
因此,如果您分配了一个变量,并且没有 global
的变量只会影响局部变量。
例如,如果您将值分配给 mySet
,那么它也不会更改。
def outerFunc():
mySet = set()
def innerFunc():
mySet = {1}
mySet.add(2)
innerFunc()
print(mySet) # ''
关于Python 内部函数集与非局部函数集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70388304/