似乎如果我通过几个文件中的import
语句导入同一个Python文件并在其中更改某个文件范围变量,那么引用更改对其他模块将不可见而容器的变化将会。从几个Python文件中更改相同的文件范围变量
例如,
第一示例
first.py
import reader
import helper
reader.change_buf('modified')
helper.foo()
second.py
import reader
def foo():
print(reader.BUF)
reader.py
buf = 'original'
def change_buf(buf):
buf = buf
输出
> python first.py
original
第二示例
first.py
import reader
import helper
reader.change_first_element('1')
helper.foo()
second.py
import reader
def foo():
print(reader.BUF)
reader.py
buf = ['0', '1', '2']
def change_first_element(new_elem):
buf[0] = new_elem
输出
> python first.py
['1', '1', '2']
为什么?