为什么Python在函数内修改外部变量时会判定为创建新局部变量?
问题根源
Python默认的变量作用域规则如下:
- 如果函数内部仅读取某个变量,优先读取全局作用域的同名变量
- 如果函数内部对某个变量执行赋值操作,Python会自动将该变量识别为局部变量,不会使用全局同名变量,这就是你遇到的无法识别外部fill、empty变量的原因
你修改后的代码仍然无效,是因为calculate返回的fill、empty没有被接收赋值给全局变量,render_function读取的还是初始的空字符串。
解决方案
方案一:传参+返回值(更推荐,逻辑更易维护)
完全规避全局变量依赖,代码逻辑更清晰:
import time import os position = [0, 1, 0] isRunning = True def calculate(): empty = "" fill = "" for x in position: render_val = x if render_val == 0: empty = "-" if render_val == 1: fill = "⬛" return fill, empty def render_function(fill, empty): if position[0] == 1: print(fill, empty) if position[0] == 0: print(empty, fill) os.system('clear') while isRunning: # 接收calculate返回的计算结果 fill, empty = calculate() # 将结果传入渲染函数 render_function(fill, empty) time.sleep(3) os.system('clear')
方案二:global声明(适合快速修改现有代码)
如果不想大幅调整现有逻辑,可以在函数内声明要使用全局变量:
import time import os ant = "#" position = [0, 1, 0] render = 0 isRunning = True fill = "" empty = "" def calculate(): # 声明以下变量使用全局作用域的同名变量 global empty, fill, render for x in position: render = x if render == 0: empty = "-" if render == 1: fill = "⬛" def render_function(): if position[0] == 1: print(fill, empty) if position[0] == 0: print(empty, fill) os.system('clear') while isRunning: calculate() render_function() time.sleep(3) os.system('clear')
内容的提问来源于stack exchange,提问作者Destiny Wotsit
相关产品推荐
相关产品推荐

