You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python中多次导入同一模块,修改一个引用的变量会影响其他引用?

Why does modifying a module attribute via one alias affect another?

I have a file abcd.py with the following content:

a=9
def funn():
    print("A")

I imported this module twice in the Python interactive shell:

>>> import abcd as ss
>>> ss.a
9
>>> import abcd as qq
>>> qq.a
9

But when I modified the value of a through ss, the value of a in qq also changed automatically:

>>> ss.a=4
>>> ss.a
4
>>> qq.a
4

Why is this happening?


Answer

Great question! This behavior comes down to a core rule of how Python handles modules: modules are singleton objects. Let me break this down in plain terms:

  • When you run import abcd as ss for the first time, Python finds abcd.py, runs all the code inside it, and creates a single module instance in your computer's memory. The variable ss is just a "pointer" pointing to this one instance.
  • When you run import abcd as qq later, Python checks and sees that abcd has already been loaded. Instead of making a brand new module instance, it just links the existing one to the new variable qq.

Put simply, ss and qq are just different names for the exact same module object in memory. So when you change ss.a = 4, you're modifying the a attribute of that single module instance. Since qq points to the same object, reading qq.a will show the updated value right away.

You can easily confirm this with a quick check in the shell:

>>> print(ss is qq)
True

The is operator verifies if two variables reference the same object—this output confirms they do.

If you want separate, independent copies of the values (so modifying one doesn't impact the other), wrap the state in a class instead. Update your abcd.py to:

class MyModuleState:
    def __init__(self):
        self.a = 9
    
    def funn(self):
        print("A")

Then use it like this:

>>> import abcd as ss
>>> state1 = ss.MyModuleState()
>>> import abcd as qq
>>> state2 = qq.MyModuleState()
>>> state1.a = 4
>>> state1.a  # Outputs 4
4
>>> state2.a  # Outputs 9, completely unaffected
9

内容的提问来源于stack exchange,提问作者user9121776

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:21:59