gpt4 book ai didi

python - 如何在嵌套函数中更改嵌套函数的变量

转载 作者:太空狗 更新时间:2023-10-29 16:53:35 26 4
gpt4 key购买 nike

我想在嵌套函数中定义要在嵌套函数中更改的变量,比如

def nesting():
count = 0
def nested():
count += 1

for i in range(10):
nested()
print count

调用嵌套函数时,我希望它打印 10,但它引发了 UnboundLocalError。关键字 global 可以解决这个问题。但由于变量 count 仅在嵌套函数的范围内使用,我希望不要将其声明为全局变量。这样做的好方法是什么?

最佳答案

在 Python 3.x 中,您可以使用 nonlocal 声明(在 nested 中)告诉 Python 您要分配给 count 嵌套中的变量。

在 Python 2.x 中,您根本无法从 nested 分配给 nesting 中的 count。但是,您可以通过不分配给变量本身而是使用可变容器来解决它:

def nesting():
count = [0]
def nested():
count[0] += 1

for i in range(10):
nested()
print count[0]

尽管对于非平凡的情况,通常的 Python 方法是将数据和功能包装在一个类中,而不是使用闭包。

关于python - 如何在嵌套函数中更改嵌套函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198709/

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