Python覆盖嵌套函数中的变量 [英] Python overwriting variables in nested functions
问题描述
假设我有以下 python 代码:
Suppose I have the following python code:
def outer():
string = ""
def inner():
string = "String was changed by a nested function!"
inner()
return string
我想调用outer()来返回字符串被嵌套函数改变了!",但我得到了".我的结论是,Python 认为 string = "string was changed by an nested function!"
行是对 inner() 局部新变量的声明.我的问题是:我如何告诉 Python 它应该使用 outer() 字符串?我不能使用 global
关键字,因为该字符串不是全局的,它只是存在于外部作用域中.想法?
I want a call to outer() to return "String was changed by a nested function!", but I get "". I conclude that Python thinks that the line string = "string was changed by a nested function!"
is a declaration of a new variable local to inner(). My question is: how do I tell Python that it should use the outer() string? I can't use the global
keyword, because the string isn't global, it just lives in an outer scope. Ideas?
推荐答案
在 Python 3.x 中,您可以使用 nonlocal
关键字:
In Python 3.x, you can use the nonlocal
keyword:
def outer():
string = ""
def inner():
nonlocal string
string = "String was changed by a nested function!"
inner()
return string
在 Python 2.x 中,您可以使用包含单个元素的列表并覆盖该单个元素:
In Python 2.x, you could use a list with a single element and overwrite that single element:
def outer():
string = [""]
def inner():
string[0] = "String was changed by a nested function!"
inner()
return string[0]
这篇关于Python覆盖嵌套函数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!