修改python import模块中的变量

可以直接通过 模块名.变量名=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

猜你喜欢

转载自www.cnblogs.com/xbit/p/10888110.html
今日推荐