可以直接通過 模塊名.變量名=xx 的方式修改模塊中的全局變量,測試代碼如下
模塊:test_model.py
x = 111 def inc_x(): global x x = x + 1
測試腳本:test.py
import test_model print('test_model.x =', test_model.x) test_model.x = 10 print('test_model.x =', test_model.x) test_model.inc_x() print('test_model.x =', test_model.x) test_model.inc_x() print('test_model.x =', test_model.x)
輸出:
test_model.x = 111 test_model.x = 10 test_model.x = 11 test_model.x = 12