Python变量赋值前引用问题:函数更新全局变量失败求解
问题解决方案
代码中的两个核心问题
- 比较运算符误用:原代码里的
<<是位左移运算符,不是小于比较,应该改成< - 全局变量修改未声明:函数内要修改全局变量
indexer,必须先通过global关键字声明,否则Python会将其视为局部变量,触发UnboundLocalError
修正后的代码(使用global关键字)
indexer = 0 my_list = ["no", "yes"] # 避免用list作为变量名,会覆盖Python内置的list类型 maybe = 1 def test(): global indexer # 声明要操作的是全局作用域的indexer if indexer < maybe: indexer = maybe print("boooo") test() print(indexer) # 输出1,验证全局变量已被修改
替代方案(无需global,更推荐)
如果不想依赖全局变量,可以通过函数返回值的方式更新变量,这种方式更符合代码封装原则,减少副作用:
indexer = 0 my_list = ["no", "yes"] maybe = 1 def test(current_index, new_index): if current_index < new_index: print("boooo") return new_index return current_index # 通过函数返回值更新indexer indexer = test(indexer, maybe) print(indexer) # 输出1
内容的提问来源于stack exchange,提问作者Sadturtle0
相关产品推荐
相关产品推荐

