gpt4 book ai didi

嵌套功能中的python覆盖变量

转载 作者:IT老高 更新时间:2023-10-28 20:28:29 26 4
gpt4 key购买 nike

假设我有以下python代码:

def outer():
string = ""
def inner():
string = "String was changed by a nested function!"
inner()
return string

我希望调用Outer()返回“字符串通过嵌套函数更改!”,但我得到了“”。我得出的结论是,Python认为行 string =“字符串通过嵌套函数更改!” 是NERT local to Inner()的新变量的声明。我的问题是:如何告诉Python应该使用outer()字符串?我不能使用 global 关键字,因为字符串不是全局,所以它只是生活在外部范围中。想法?

最佳答案

在Python 3.x中,您可以使用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]

关于嵌套功能中的python覆盖变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7935966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com