python - variable change in nested func not recognized in other func with variable passed as arg
问题描述
I have the following simplified version of my code:
import time
def inner(condition, callback):
while condition:
print('test')
time.sleep(1)
callback()
def outer():
condition = True
def callback():
nonlocal condition
condition = False
inner(condition, callback)
outer()
Currently, the above code continues to print, even though i change the condition variable to false in the callback function. I want the condition to change to False, and the while loop to exit.
How come the variable change is not detected in the inner func?
解决方案
那是因为condition
ininner()
是一个局部变量,callback()
改变了condition
的第一行中定义的outer()
,但不能改变 的局部变量inner()
。因此, 中的条件inner
将始终为True
。这可以通过以下代码验证
def inner(condition, callback):
# while condition:
# print('test')
# time.sleep(1)
# callback()
print('condition in inner before callback(): {}'.format(condition))
callback()
print('condition in inner after callback(): {}'.format(condition))
def outer():
condition = True
def callback():
nonlocal condition
condition = False
inner(condition, callback)
print('condition in outer after callback() called in inner: {}'.format(condition))
outer()
一种解决方法是将 更改condition
为列表:[True]
. List 是python中的可变对象,这意味着改变它的元素不会改变它在内存中的地址,condition
ininner()
不断更新condition
in outer()
:
def inner(condition, callback):
while condition[0]:
print('test')
time.sleep(1)
callback()
def outer():
condition = [True]
def callback():
nonlocal condition
condition[0] = False
inner(condition, callback)
outer()
推荐阅读
- python - 任何人都可以帮助解决我的 python 批处理文件的问题吗?CMD首先显示空白屏幕
- r - 什么 ggplot 函数允许在不影响原始图的原始 lims/labels/panel 的情况下添加二次美学?
- python - 如何从 Kubernetes 向 Delta Lake 写入数据
- r - 与 data.frame 中的列关联的所有行
- scroll - 如何抓取不使用 AJAX 和 Scrapy 的无限滚动页面?
- nlp - NLP去除错别字的方法?
- java - Java 垃圾收集延迟
- json - schema-registry JSON Schema FULL 兼容性检查
- google-sheets - ARRAYFORMULA 不适用于包含 IF 和 COUNTIF 的自定义公式
- c# - 我无法通过 Visual Studio 或我的应用程序连接到数据库,但我可以连接到 mysql 工作台