假设我有以下python代码:
def outer(): string = "" def inner(): string = "String was changed by a nested function!" inner() return string
我想调用external()返回“字符串已被嵌套函数更改!”,但我得到了“”。我得出结论,Python认为该行string = "string was changed by a nested function!"是对inner()局部的新变量的声明。我的问题是:如何告诉Python应该使用external()字符串?我不能使用global关键字,因为字符串不是全局的,它只存在于外部作用域中。有想法吗?
string = "string was changed by a nested function!"
global
在Python 3.x中,可以使用nonlocal关键字:
nonlocal
def outer(): string = "" def inner(): nonlocal string string = "String was changed by a nested function!" inner() return string
在Python 2.x中,您可以使用带有单个元素的列表并覆盖该单个元素:
def outer(): string = [""] def inner(): string[0] = "String was changed by a nested function!" inner() return string[0]