【发布时间】:2021-06-28 19:53:59
【问题描述】:
我有 2 个文件,比如 a.py 和 b.py,b.py 有一个全局变量,比如 test(数据类型是字符串),我在 a.py 中导入 test .现在,在运行时,a.py 中的一个函数调用了b.py 的一个函数,并且该函数更改了b.py 中test 的值,但是这个更改没有显示在a.py 中,因为测试是字符串数据类型和字符串是不可变的。
我尝试使用列表,它可以工作,但我对使用包含一个元素的列表感觉不太好。那么,是否有任何可变数据类型(类似于字符串)可以用于此目的?
test 为字符串时的代码。
b.py
test = "hello"
def changeTest():
global test
test = "hii"
a.py
from b import test,changeTest
def callFunctionInB():
changeTest()
print(test)
callFunctionInB()
print(test)
输出:
hello
hello
测试列表时的代码。
b.py
test = ["hello"]
def changeTest():
test[0] = "hii"
a.py
from b import test,changeTest
def callFunctionInB():
changeTest()
print(test)
callFunctionInB()
print(test)
输出:
['hello']
['hii']
【问题讨论】:
标签: python-3.x string import python-module mutable