为何Python中多次导入同一模块,修改一个引用的变量会影响其他引用?
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 ssfor the first time, Python findsabcd.py, runs all the code inside it, and creates a single module instance in your computer's memory. The variablessis just a "pointer" pointing to this one instance. - When you run
import abcd as qqlater, Python checks and sees thatabcdhas already been loaded. Instead of making a brand new module instance, it just links the existing one to the new variableqq.
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

