【发布时间】:2021-10-27 23:37:30
【问题描述】:
我有两个脚本test1.py和test2.py,内容如下:
# test1.py
box = []
def run():
box.append(20)
box.append(30)
print(box)
print(f'test1 {id(box)}')
from test2 import b
print(b)
if __name__ == '__main__':
run()
# test2.py
from test1 import box
print(f'test2 {id(box)}')
box.append(40)
b = box
这是我运行test1.py时得到的结果:
[20, 30]
test1 4320983560
test2 4320994504
[40]
在我看来box是一个可变对象,所以最终结果应该是[20, 30, 40],但实际上test1.py和test2.py中的box有不同的id,看起来也不一样.这让我很困惑,谁能告诉我为什么?
【问题讨论】:
-
请不要以照片形式发送代码,以代码块形式发送
-
请避免posting images of text。最好是转录它们。
-
运行test2.py的结果如何??我认为您的意思是运行 test1.py
-
顺便说一句。好问题。我从一个模块中导入了一个列表,它在两个脚本中具有相同的地址。你的情况很有趣。
标签: python