【问题标题】:Why list cross files have different id? [duplicate]为什么列表交叉文件有不同的ID? [复制]
【发布时间】:2021-10-27 23:37:30
【问题描述】:

我有两个脚本test1.pytest2.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.pytest2.py中的box有不同的id,看起来也不一样.这让我很困惑,谁能告诉我为什么?

【问题讨论】:

  • 请不要以照片形式发送代码,以代码块形式发送
  • 请避免posting images of text。最好是转录它们。
  • 运行test2.py的结果如何??我认为您的意思是运行 test1.py
  • 顺便说一句。好问题。我从一个模块中导入了一个列表,它在两个脚本中具有相同的地址。你的情况很有趣。

标签: python


【解决方案1】:

test2.py 中,当您导入test1 时,它会进入文件,并导入a,就像第一行所说的那样:

a = []

你先跑没关系 test1.py 脚本并从中导入 test2。一次

from test1 import a

被导入,你只导入一个空列表。它也没有使用run 函数,只有在没有导入test1 时才会发生这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多